home *** CD-ROM | disk | FTP | other *** search
/ Ultra Pack / UltraComputing Partner Applications.iso / SunLabs / tclTK / src / tk4.0 / tkImgPhoto.c < prev    next >
Encoding:
C/C++ Source or Header  |  1995-06-21  |  113.0 KB  |  4,060 lines

  1. /*
  2.  * tkImgPhoto.c --
  3.  *
  4.  *    Implements images of type "photo" for Tk.  Photo images are
  5.  *    stored in full color (24 bits per pixel) and displayed using
  6.  *    dithering if necessary.
  7.  *
  8.  * Copyright (c) 1994 The Australian National University.
  9.  * Copyright (c) 1994-1995 Sun Microsystems, Inc.
  10.  *
  11.  * See the file "license.terms" for information on usage and redistribution
  12.  * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
  13.  *
  14.  * Author: Paul Mackerras (paulus@cs.anu.edu.au),
  15.  *       Department of Computer Science,
  16.  *       Australian National University.
  17.  */
  18.  
  19. static char sccsid[] = "@(#) tkImgPhoto.c 1.25 95/06/21 15:46:57";
  20.  
  21. #include "tkInt.h"
  22. #include "tkPort.h"
  23. #include <math.h>
  24. #include <ctype.h>
  25.  
  26. /*
  27.  * Declaration for internal Xlib function used here:
  28.  */
  29.  
  30. extern _XInitImageFuncPtrs _ANSI_ARGS_((XImage *image));
  31.  
  32. /*
  33.  * A signed 8-bit integral type.  If chars are unsigned and the compiler
  34.  * isn't an ANSI one, then we have to use short instead (which wastes
  35.  * space) to get signed behavior.
  36.  */
  37.  
  38. #ifdef __STDC__
  39.     typedef signed char schar;
  40. #else
  41. #   ifndef CHAR_UNSIGNED
  42.     typedef char schar;
  43. #   else
  44.     typedef short schar;
  45. #   endif
  46. #endif
  47.  
  48. /*
  49.  * An unsigned 32-bit integral type, used for pixel values.
  50.  * We use int rather than long here to accommodate those systems
  51.  * where longs are 64 bits.
  52.  */
  53.  
  54. typedef unsigned int pixel;
  55.  
  56. /*
  57.  * The maximum number of pixels to transmit to the server in a
  58.  * single XPutImage call.
  59.  */
  60.  
  61. #define MAX_PIXELS 65536
  62.  
  63. /*
  64.  * The set of colors required to display a photo image in a window depends on:
  65.  *    - the visual used by the window
  66.  *    - the palette, which specifies how many levels of each primary
  67.  *      color to use, and
  68.  *    - the gamma value for the image.
  69.  *
  70.  * Pixel values allocated for specific colors are valid only for the
  71.  * colormap in which they were allocated.  Sets of pixel values
  72.  * allocated for displaying photos are re-used in other windows if
  73.  * possible, that is, if the display, colormap, palette and gamma
  74.  * values match.  A hash table is used to locate these sets of pixel
  75.  * values, using the following data structure as key:
  76.  */
  77.  
  78. typedef struct {
  79.     Display *display;        /* Qualifies the colormap resource ID */
  80.     Colormap colormap;        /* Colormap that the windows are using. */
  81.     double gamma;        /* Gamma exponent value for images. */
  82.     Tk_Uid palette;        /* Specifies how many shades of each primary
  83.                  * we want to allocate. */
  84. } ColorTableId;
  85.  
  86. /*
  87.  * For a particular (display, colormap, palette, gamma) combination,
  88.  * a data structure of the following type is used to store the allocated
  89.  * pixel values and other information:
  90.  */
  91.  
  92. typedef struct ColorTable {
  93.     ColorTableId id;        /* Information used in selecting this
  94.                  * color table. */
  95.     int    flags;            /* See below. */
  96.     int    refCount;        /* Number of instances using this map. */
  97.     int liveRefCount;        /* Number of instances which are actually
  98.                  * in use, using this map. */
  99.     int    numColors;        /* Number of colors allocated for this map. */
  100.  
  101.     XVisualInfo    visualInfo;    /* Information about the visual for windows
  102.                  * using this color table. */
  103.  
  104.     pixel redValues[256];    /* Maps 8-bit values of red intensity
  105.                  * to a pixel value or index in pixelMap. */
  106.     pixel greenValues[256];    /* Ditto for green intensity */
  107.     pixel blueValues[256];    /* Ditto for blue intensity */
  108.     unsigned long *pixelMap;    /* Actual pixel values allocated. */
  109.  
  110.     unsigned char colorQuant[3][256];
  111.                 /* Maps 8-bit intensities to quantized
  112.                  * intensities.  The first index is 0 for
  113.                  * red, 1 for green, 2 for blue. */
  114. } ColorTable;
  115.  
  116. /*
  117.  * Bit definitions for the flags field of a ColorTable.
  118.  * BLACK_AND_WHITE:        1 means only black and white colors are
  119.  *                available.
  120.  * COLOR_WINDOW:        1 means a full 3-D color cube has been
  121.  *                allocated.
  122.  * DISPOSE_PENDING:        1 means a call to DisposeColorTable has
  123.  *                been scheduled as an idle handler, but it
  124.  *                hasn't been invoked yet.
  125.  * MAP_COLORS:            1 means pixel values should be mapped
  126.  *                through pixelMap.
  127.  */
  128.  
  129. #define BLACK_AND_WHITE        1
  130. #define COLOR_WINDOW        2
  131. #define DISPOSE_PENDING        4
  132. #define MAP_COLORS        8
  133.  
  134. /*
  135.  * Definition of the data associated with each photo image master.
  136.  */
  137.  
  138. typedef struct PhotoMaster {
  139.     Tk_ImageMaster tkMaster;    /* Tk's token for image master.  NULL means
  140.                  * the image is being deleted. */
  141.     Tcl_Interp *interp;        /* Interpreter associated with the
  142.                  * application using this image. */
  143.     Tcl_Command imageCmd;    /* Token for image command (used to delete
  144.                  * it when the image goes away).  NULL means
  145.                  * the image command has already been
  146.                  * deleted. */
  147.     int    flags;            /* Sundry flags, defined below. */
  148.     int    width, height;        /* Dimensions of image. */
  149.     int userWidth, userHeight;    /* User-declared image dimensions. */
  150.     Tk_Uid palette;        /* User-specified default palette for
  151.                  * instances of this image. */
  152.     double gamma;        /* Display gamma value to correct for. */
  153.     char *fileString;        /* Name of file to read into image. */
  154.     char *dataString;        /* String value to use as contents of image. */
  155.     char *format;        /* User-specified format of data in image
  156.                  * file or string value. */
  157.     unsigned char *pix24;    /* Local storage for 24-bit image. */
  158.     int ditherX, ditherY;    /* Location of first incorrectly
  159.                  * dithered pixel in image. */
  160.     Region validRegion;        /* X region indicating which parts of
  161.                  * the image have valid image data. */
  162.     struct PhotoInstance *instancePtr;
  163.                 /* First in the list of instances
  164.                  * associated with this master. */
  165. } PhotoMaster;
  166.  
  167. /*
  168.  * Bit definitions for the flags field of a PhotoMaster.
  169.  * COLOR_IMAGE:            1 means that the image has different color
  170.  *                components.
  171.  * IMAGE_CHANGED:        1 means that the instances of this image
  172.  *                need to be redithered.
  173.  */
  174.  
  175. #define COLOR_IMAGE        1
  176. #define IMAGE_CHANGED        2
  177.  
  178. /*
  179.  * The following data structure represents all of the instances of
  180.  * a photo image in windows on a given screen that are using the
  181.  * same colormap.
  182.  */
  183.  
  184. typedef struct PhotoInstance {
  185.     PhotoMaster *masterPtr;    /* Pointer to master for image. */
  186.     Display *display;        /* Display for windows using this instance. */
  187.     Colormap colormap;        /* The image may only be used in windows with
  188.                  * this particular colormap. */
  189.     struct PhotoInstance *nextPtr;
  190.                 /* Pointer to the next instance in the list
  191.                  * of instances associated with this master. */
  192.     int refCount;        /* Number of instances using this structure. */
  193.     Tk_Uid palette;        /* Palette for these particular instances. */
  194.     double gamma;        /* Gamma value for these instances. */
  195.     Tk_Uid defaultPalette;    /* Default palette to use if a palette
  196.                  * is not specified for the master. */
  197.     ColorTable *colorTablePtr;    /* Pointer to information about colors
  198.                  * allocated for image display in windows
  199.                  * like this one. */
  200.     Pixmap pixels;        /* X pixmap containing dithered image. */
  201.     int width, height;        /* Dimensions of the pixmap. */
  202.     schar *error;        /* Error image, used in dithering. */
  203.     XImage *imagePtr;        /* Image structure for converted pixels. */
  204.     XVisualInfo visualInfo;    /* Information about the visual that these
  205.                  * windows are using. */
  206.     GC gc;            /* Graphics context for writing images
  207.                  * to the pixmap. */
  208. } PhotoInstance;
  209.  
  210. /*
  211.  * The following data structure is used to return information
  212.  * from ParseSubcommandOptions:
  213.  */
  214.  
  215. struct SubcommandOptions {
  216.     int options;        /* Individual bits indicate which
  217.                  * options were specified - see below. */
  218.     char *name;            /* Name specified without an option. */
  219.     int fromX, fromY;        /* Values specified for -from option. */
  220.     int fromX2, fromY2;        /* Second coordinate pair for -from option. */
  221.     int toX, toY;        /* Values specified for -to option. */
  222.     int toX2, toY2;        /* Second coordinate pair for -to option. */
  223.     int zoomX, zoomY;        /* Values specified for -zoom option. */
  224.     int subsampleX, subsampleY;    /* Values specified for -subsample option. */
  225.     char *format;        /* Value specified for -format option. */
  226. };
  227.  
  228. /*
  229.  * Bit definitions for use with ParseSubcommandOptions:
  230.  * Each bit is set in the allowedOptions parameter on a call to
  231.  * ParseSubcommandOptions if that option is allowed for the current
  232.  * photo image subcommand.  On return, the bit is set in the options
  233.  * field of the SubcommandOptions structure if that option was specified.
  234.  *
  235.  * OPT_FORMAT:            Set if -format option allowed/specified.
  236.  * OPT_FROM:            Set if -from option allowed/specified.
  237.  * OPT_SHRINK:            Set if -shrink option allowed/specified.
  238.  * OPT_SUBSAMPLE:        Set if -subsample option allowed/spec'd.
  239.  * OPT_TO:            Set if -to option allowed/specified.
  240.  * OPT_ZOOM:            Set if -zoom option allowed/specified.
  241.  */
  242.  
  243. #define OPT_FORMAT    1
  244. #define OPT_FROM    2
  245. #define OPT_SHRINK    4
  246. #define OPT_SUBSAMPLE    8
  247. #define OPT_TO        0x10
  248. #define OPT_ZOOM    0x20
  249.  
  250. /*
  251.  * List of option names.  The order here must match the order of
  252.  * declarations of the OPT_* constants above.
  253.  */
  254.  
  255. static char *optionNames[] = {
  256.     "-format",
  257.     "-from",
  258.     "-shrink",
  259.     "-subsample",
  260.     "-to",
  261.     "-zoom",
  262.     (char *) NULL
  263. };
  264.  
  265. /*
  266.  * The type record for photo images:
  267.  */
  268.  
  269. static int        ImgPhotoCreate _ANSI_ARGS_((Tcl_Interp *interp,
  270.                 char *name, int argc, char **argv,
  271.                 Tk_ImageType *typePtr, Tk_ImageMaster master,
  272.                 ClientData *clientDataPtr));
  273. static ClientData    ImgPhotoGet _ANSI_ARGS_((Tk_Window tkwin,
  274.                 ClientData clientData));
  275. static void        ImgPhotoDisplay _ANSI_ARGS_((ClientData clientData,
  276.                 Display *display, Drawable drawable,
  277.                 int imageX, int imageY, int width, int height,
  278.                 int drawableX, int drawableY));
  279. static void        ImgPhotoFree _ANSI_ARGS_((ClientData clientData,
  280.                 Display *display));
  281. static void        ImgPhotoDelete _ANSI_ARGS_((ClientData clientData));
  282.  
  283. Tk_ImageType tkPhotoImageType = {
  284.     "photo",            /* name */
  285.     ImgPhotoCreate,        /* createProc */
  286.     ImgPhotoGet,        /* getProc */
  287.     ImgPhotoDisplay,        /* displayProc */
  288.     ImgPhotoFree,        /* freeProc */
  289.     ImgPhotoDelete,        /* deleteProc */
  290.     (Tk_ImageType *) NULL    /* nextPtr */
  291. };
  292.  
  293. /*
  294.  * Default configuration
  295.  */
  296.  
  297. #define DEF_PHOTO_GAMMA        "1"
  298. #define DEF_PHOTO_HEIGHT    "0"
  299. #define DEF_PHOTO_PALETTE    ""
  300. #define DEF_PHOTO_WIDTH        "0"
  301.  
  302. /*
  303.  * Information used for parsing configuration specifications:
  304.  */
  305. static Tk_ConfigSpec configSpecs[] = {
  306.     {TK_CONFIG_STRING, "-data", (char *) NULL, (char *) NULL,
  307.      (char *) NULL, Tk_Offset(PhotoMaster, dataString), TK_CONFIG_NULL_OK},
  308.     {TK_CONFIG_STRING, "-format", (char *) NULL, (char *) NULL,
  309.      (char *) NULL, Tk_Offset(PhotoMaster, format), TK_CONFIG_NULL_OK},
  310.     {TK_CONFIG_STRING, "-file", (char *) NULL, (char *) NULL,
  311.      (char *) NULL, Tk_Offset(PhotoMaster, fileString), TK_CONFIG_NULL_OK},
  312.     {TK_CONFIG_DOUBLE, "-gamma", (char *) NULL, (char *) NULL,
  313.      DEF_PHOTO_GAMMA, Tk_Offset(PhotoMaster, gamma), 0},
  314.     {TK_CONFIG_INT, "-height", (char *) NULL, (char *) NULL,
  315.      DEF_PHOTO_HEIGHT, Tk_Offset(PhotoMaster, userHeight), 0},
  316.     {TK_CONFIG_UID, "-palette", (char *) NULL, (char *) NULL,
  317.      DEF_PHOTO_PALETTE, Tk_Offset(PhotoMaster, palette), 0},
  318.     {TK_CONFIG_INT, "-width", (char *) NULL, (char *) NULL,
  319.      DEF_PHOTO_WIDTH, Tk_Offset(PhotoMaster, userWidth), 0},
  320.     {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL,
  321.      (char *) NULL, 0, 0}
  322. };
  323.  
  324. /*
  325.  * Hash table used to provide access to photo images from C code.
  326.  */
  327.  
  328. static Tcl_HashTable imgPhotoHash;
  329. static int imgPhotoHashInitialized;    /* set when Tcl_InitHashTable done */
  330.  
  331. /*
  332.  * Hash table used to hash from (display, colormap, palette, gamma)
  333.  * to ColorTable address.
  334.  */
  335.  
  336. static Tcl_HashTable imgPhotoColorHash;
  337. static int imgPhotoColorHashInitialized;
  338. #define N_COLOR_HASH    (sizeof(ColorTableId) / sizeof(int))
  339.  
  340. /*
  341.  * Pointer to the first in the list of known photo image formats.
  342.  */
  343.  
  344. static Tk_PhotoImageFormat *formatList = NULL;
  345.  
  346. /*
  347.  * Forward declarations
  348.  */
  349.  
  350. static int        ImgPhotoCmd _ANSI_ARGS_((ClientData clientData,
  351.                 Tcl_Interp *interp, int argc, char **argv));
  352. static int        ParseSubcommandOptions _ANSI_ARGS_((
  353.                 struct SubcommandOptions *optPtr,
  354.                 Tcl_Interp *interp, int allowedOptions,
  355.                 int *indexPtr, int argc, char **argv));
  356. static void        ImgPhotoCmdDeletedProc _ANSI_ARGS_((
  357.                 ClientData clientData));
  358. static int        ImgPhotoConfigureMaster _ANSI_ARGS_((
  359.                 Tcl_Interp *interp, PhotoMaster *masterPtr,
  360.                 int argc, char **argv, int flags));
  361. static void        ImgPhotoConfigureInstance _ANSI_ARGS_((
  362.                 PhotoInstance *instancePtr));
  363. static void        ImgPhotoSetSize _ANSI_ARGS_((PhotoMaster *masterPtr,
  364.                 int width, int height));
  365. static void        ImgPhotoInstanceSetSize _ANSI_ARGS_((
  366.                 PhotoInstance *instancePtr));
  367. static int        IsValidPalette _ANSI_ARGS_((PhotoInstance *instancePtr,
  368.                 char *palette));
  369. static int        CountBits _ANSI_ARGS_((pixel mask));
  370. static void        GetColorTable _ANSI_ARGS_((PhotoInstance *instancePtr));
  371. static void        FreeColorTable _ANSI_ARGS_((ColorTable *colorPtr));
  372. static void        AllocateColors _ANSI_ARGS_((ColorTable *colorPtr));
  373. static void        DisposeColorTable _ANSI_ARGS_((ClientData clientData));
  374. static void        DisposeInstance _ANSI_ARGS_((ClientData clientData));
  375. static int        ReclaimColors _ANSI_ARGS_((ColorTableId *id,
  376.                 int numColors));
  377. static int        MatchFileFormat _ANSI_ARGS_((Tcl_Interp *interp,
  378.                 FILE *f, char *fileName, char *formatString,
  379.                 Tk_PhotoImageFormat **imageFormatPtr,
  380.                 int *widthPtr, int *heightPtr));
  381. static int        MatchStringFormat _ANSI_ARGS_((Tcl_Interp *interp,
  382.                 char *string, char *formatString,
  383.                 Tk_PhotoImageFormat **imageFormatPtr,
  384.                 int *widthPtr, int *heightPtr));
  385. static void        Dither _ANSI_ARGS_((PhotoMaster *masterPtr,
  386.                 int x, int y, int width, int height));
  387. static void        DitherInstance _ANSI_ARGS_((PhotoInstance *instancePtr,
  388.                 int x, int y, int width, int height));
  389.  
  390. #undef MIN
  391. #define MIN(a, b)    ((a) < (b)? (a): (b))
  392. #undef MAX
  393. #define MAX(a, b)    ((a) > (b)? (a): (b))
  394.  
  395. /*
  396.  *----------------------------------------------------------------------
  397.  *
  398.  * Tk_CreatePhotoImageFormat --
  399.  *
  400.  *    This procedure is invoked by an image file handler to register
  401.  *    a new photo image format and the procedures that handle the
  402.  *    new format.  The procedure is typically invoked during
  403.  *    Tcl_AppInit.
  404.  *
  405.  * Results:
  406.  *    None.
  407.  *
  408.  * Side effects:
  409.  *    The new image file format is entered into a table used in the
  410.  *    photo image "read" and "write" subcommands.
  411.  *
  412.  *----------------------------------------------------------------------
  413.  */
  414.  
  415. void
  416. Tk_CreatePhotoImageFormat(formatPtr)
  417.     Tk_PhotoImageFormat *formatPtr;
  418.                 /* Structure describing the format.  All of
  419.                  * the fields except "nextPtr" must be filled
  420.                  * in by caller.  Must not have been passed
  421.                  * to Tk_CreatePhotoImageFormat previously. */
  422. {
  423.     Tk_PhotoImageFormat *copyPtr;
  424.  
  425.     copyPtr = (Tk_PhotoImageFormat *) ckalloc(sizeof(Tk_PhotoImageFormat));
  426.     *copyPtr = *formatPtr;
  427.     copyPtr->name = (char *) ckalloc((unsigned) (strlen(formatPtr->name) + 1));
  428.     strcpy(copyPtr->name, formatPtr->name);
  429.     copyPtr->nextPtr = formatList;
  430.     formatList = copyPtr;
  431. }
  432.  
  433. /*
  434.  *----------------------------------------------------------------------
  435.  *
  436.  * ImgPhotoCreate --
  437.  *
  438.  *    This procedure is called by the Tk image code to create
  439.  *    a new photo image.
  440.  *
  441.  * Results:
  442.  *    A standard Tcl result.
  443.  *
  444.  * Side effects:
  445.  *    The data structure for a new photo image is allocated and
  446.  *    initialized.
  447.  *
  448.  *----------------------------------------------------------------------
  449.  */
  450.  
  451. static int
  452. ImgPhotoCreate(interp, name, argc, argv, typePtr, master, clientDataPtr)
  453.     Tcl_Interp *interp;        /* Interpreter for application containing
  454.                  * image. */
  455.     char *name;            /* Name to use for image. */
  456.     int argc;            /* Number of arguments. */
  457.     char **argv;        /* Argument strings for options (doesn't
  458.                  * include image name or type). */
  459.     Tk_ImageType *typePtr;    /* Pointer to our type record (not used). */
  460.     Tk_ImageMaster master;    /* Token for image, to be used by us in
  461.                  * later callbacks. */
  462.     ClientData *clientDataPtr;    /* Store manager's token for image here;
  463.                  * it will be returned in later callbacks. */
  464. {
  465.     PhotoMaster *masterPtr;
  466.     Tcl_HashEntry *entry;
  467.     int isNew;
  468.  
  469.     /*
  470.      * Allocate and initialize the photo image master record.
  471.      */
  472.  
  473.     masterPtr = (PhotoMaster *) ckalloc(sizeof(PhotoMaster));
  474.     memset((void *) masterPtr, 0, sizeof(PhotoMaster));
  475.     masterPtr->tkMaster = master;
  476.     masterPtr->interp = interp;
  477.     masterPtr->imageCmd = Tcl_CreateCommand(interp, name, ImgPhotoCmd,
  478.         (ClientData) masterPtr, ImgPhotoCmdDeletedProc);
  479.     masterPtr->palette = NULL;
  480.     masterPtr->pix24 = NULL;
  481.     masterPtr->instancePtr = NULL;
  482.     masterPtr->validRegion = XCreateRegion();
  483.  
  484.     /*
  485.      * Process configuration options given in the image create command.
  486.      */
  487.  
  488.     if (ImgPhotoConfigureMaster(interp, masterPtr, argc, argv, 0) != TCL_OK) {
  489.     ImgPhotoDelete((ClientData) masterPtr);
  490.     return TCL_ERROR;
  491.     }
  492.  
  493.     /*
  494.      * Enter this photo image in the hash table.
  495.      */
  496.  
  497.     if (!imgPhotoHashInitialized) {
  498.     Tcl_InitHashTable(&imgPhotoHash, TCL_STRING_KEYS);
  499.     imgPhotoHashInitialized = 1;
  500.     }
  501.     entry = Tcl_CreateHashEntry(&imgPhotoHash, name, &isNew);
  502.     Tcl_SetHashValue(entry, masterPtr);
  503.  
  504.     *clientDataPtr = (ClientData) masterPtr;
  505.     return TCL_OK;
  506. }
  507.  
  508. /*
  509.  *----------------------------------------------------------------------
  510.  *
  511.  * ImgPhotoCmd --
  512.  *
  513.  *    This procedure is invoked to process the Tcl command that
  514.  *    corresponds to a photo image.  See the user documentation
  515.  *    for details on what it does.
  516.  *
  517.  * Results:
  518.  *    A standard Tcl result.
  519.  *
  520.  * Side effects:
  521.  *    See the user documentation.
  522.  *
  523.  *----------------------------------------------------------------------
  524.  */
  525.  
  526. static int
  527. ImgPhotoCmd(clientData, interp, argc, argv)
  528.     ClientData clientData;    /* Information about photo master. */
  529.     Tcl_Interp *interp;        /* Current interpreter. */
  530.     int argc;            /* Number of arguments. */
  531.     char **argv;        /* Argument strings. */
  532. {
  533.     PhotoMaster *masterPtr = (PhotoMaster *) clientData;
  534.     int c, result, index;
  535.     int x, y, width, height;
  536.     int dataWidth, dataHeight;
  537.     struct SubcommandOptions options;
  538.     int listArgc;
  539.     char **listArgv;
  540.     char **srcArgv;
  541.     unsigned char *pixelPtr;
  542.     Tk_PhotoImageBlock block;
  543.     Tk_Window tkwin;
  544.     char string[16];
  545.     XColor color;
  546.     Tk_PhotoImageFormat *imageFormat;
  547.     int imageWidth, imageHeight;
  548.     int matched;
  549.     FILE *f;
  550.     Tk_PhotoHandle srcHandle;
  551.     size_t length;
  552.     Tcl_DString buffer;
  553.     char *realFileName;
  554.  
  555.     if (argc < 2) {
  556.     Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  557.         " option ?arg arg ...?\"", (char *) NULL);
  558.     return TCL_ERROR;
  559.     }
  560.     c = argv[1][0];
  561.     length = strlen(argv[1]);
  562.  
  563.     if ((c == 'b') && (strncmp(argv[1], "blank", length) == 0)) {
  564.     /*
  565.      * photo blank command - just call Tk_PhotoBlank.
  566.      */
  567.  
  568.     if (argc == 2) {
  569.         Tk_PhotoBlank(masterPtr);
  570.     } else {
  571.         Tcl_AppendResult(interp, "wrong # args: should be \"",
  572.             argv[0], " blank\"", (char *) NULL);
  573.         return TCL_ERROR;
  574.     }
  575.     } else if ((c == 'c') && (length >= 2)
  576.         && (strncmp(argv[1], "cget", length) == 0)) {
  577.     if (argc != 3) {
  578.         Tcl_AppendResult(interp, "wrong # args: should be \"",
  579.             argv[0], " cget option\"",
  580.             (char *) NULL);
  581.         return TCL_ERROR;
  582.     }
  583.     result = Tk_ConfigureValue(interp, Tk_MainWindow(interp), configSpecs,
  584.         (char *) masterPtr, argv[2], 0);
  585.     } else if ((c == 'c') && (length >= 3)
  586.         && (strncmp(argv[1], "configure", length) == 0)) {
  587.     /*
  588.      * photo configure command - handle this in the standard way.
  589.      */
  590.  
  591.     if (argc == 2) {
  592.         return Tk_ConfigureInfo(interp, Tk_MainWindow(interp),
  593.             configSpecs, (char *) masterPtr, (char *) NULL, 0);
  594.     }
  595.     if (argc == 3) {
  596.         return Tk_ConfigureInfo(interp, Tk_MainWindow(interp),
  597.             configSpecs, (char *) masterPtr, argv[2], 0);
  598.     }
  599.     return ImgPhotoConfigureMaster(interp, masterPtr, argc-2, argv+2,
  600.         TK_CONFIG_ARGV_ONLY);
  601.     } else if ((c == 'c') && (length >= 3)
  602.         && (strncmp(argv[1], "copy", length) == 0)) {
  603.     /*
  604.      * photo copy command - first parse options.
  605.      */
  606.  
  607.     index = 2;
  608.     memset((VOID *) &options, 0, sizeof(options));
  609.     options.zoomX = options.zoomY = 1;
  610.     options.subsampleX = options.subsampleY = 1;
  611.     options.name = NULL;
  612.     if (ParseSubcommandOptions(&options, interp,
  613.         OPT_FROM | OPT_TO | OPT_ZOOM | OPT_SUBSAMPLE | OPT_SHRINK,
  614.         &index, argc, argv) != TCL_OK) {
  615.         return TCL_ERROR;
  616.     }
  617.     if (options.name == NULL || index < argc) {
  618.         Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  619.             " copy source-image ?-from x1 y1 x2 y2?",
  620.             " ?-to x1 y1 x2 y2? ?-zoom x y? ?-subsample x y?",
  621.             "\"", (char *) NULL);
  622.         return TCL_ERROR;
  623.     }
  624.  
  625.     /*
  626.      * Look for the source image and get a pointer to its image data.
  627.      * Check the values given for the -from option.
  628.      */
  629.  
  630.     if ((srcHandle = Tk_FindPhoto(options.name)) == NULL) {
  631.         Tcl_AppendResult(interp, "image \"", argv[2], "\" doesn't",
  632.             " exist or is not a photo image", (char *) NULL);
  633.         return TCL_ERROR;
  634.     }
  635.     Tk_PhotoGetImage(srcHandle, &block);
  636.     if ((options.fromX2 > block.width) || (options.fromY2 > block.height)
  637.         || (options.fromX2 > block.width)
  638.         || (options.fromY2 > block.height)) {
  639.         Tcl_AppendResult(interp, "coordinates for -from option extend ",
  640.             "outside source image", (char *) NULL);
  641.         return TCL_ERROR;
  642.     }
  643.  
  644.     /*
  645.      * Fill in default values for unspecified parameters.
  646.      */
  647.  
  648.     if (((options.options & OPT_FROM) == 0) || (options.fromX2 < 0)) {
  649.         options.fromX2 = block.width;
  650.         options.fromY2 = block.height;
  651.     }
  652.     if (((options.options & OPT_TO) == 0) || (options.toX2 < 0)) {
  653.         width = options.fromX2 - options.fromX;
  654.         if (options.subsampleX > 0) {
  655.         width = (width + options.subsampleX - 1) / options.subsampleX;
  656.         } else if (options.subsampleX == 0) {
  657.         width = 0;
  658.         } else {
  659.         width = (width - options.subsampleX - 1) / -options.subsampleX;
  660.         }
  661.         options.toX2 = options.toX + width * options.zoomX;
  662.  
  663.         height = options.fromY2 - options.fromY;
  664.         if (options.subsampleY > 0) {
  665.         height = (height + options.subsampleY - 1)
  666.             / options.subsampleY;
  667.         } else if (options.subsampleY == 0) {
  668.         height = 0;
  669.         } else {
  670.         height = (height - options.subsampleY - 1)
  671.             / -options.subsampleY;
  672.         }
  673.         options.toY2 = options.toY + height * options.zoomY;
  674.     }
  675.  
  676.     /*
  677.      * Set the destination image size if the -shrink option was specified.
  678.      */
  679.  
  680.     if (options.options & OPT_SHRINK) {
  681.         ImgPhotoSetSize(masterPtr, options.toX2, options.toY2);
  682.     }
  683.  
  684.     /*
  685.      * Copy the image data over using Tk_PhotoPutZoomedBlock.
  686.      */
  687.  
  688.     block.pixelPtr += options.fromX * block.pixelSize
  689.         + options.fromY * block.pitch;
  690.     block.width = options.fromX2 - options.fromX;
  691.     block.height = options.fromY2 - options.fromY;
  692.     Tk_PhotoPutZoomedBlock((Tk_PhotoHandle) masterPtr, &block,
  693.         options.toX, options.toY, options.toX2 - options.toX,
  694.         options.toY2 - options.toY, options.zoomX, options.zoomY,
  695.         options.subsampleX, options.subsampleY);
  696.  
  697.     } else if ((c == 'g') && (strncmp(argv[1], "get", length) == 0)) {
  698.     /*
  699.      * photo get command - first parse and check parameters.
  700.      */
  701.  
  702.     if (argc != 4) {
  703.         Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  704.             " get x y\"", (char *) NULL);
  705.         return TCL_ERROR;
  706.     }
  707.     if ((Tcl_GetInt(interp, argv[2], &x) != TCL_OK)
  708.         || (Tcl_GetInt(interp, argv[3], &y) != TCL_OK)) {
  709.         return TCL_ERROR;
  710.     }
  711.     if ((x < 0) || (x >= masterPtr->width)
  712.         || (y < 0) || (y >= masterPtr->height)) {
  713.         Tcl_AppendResult(interp, argv[0], " get: ",
  714.             "coordinates out of range", (char *) NULL);
  715.         return TCL_ERROR;
  716.     }
  717.  
  718.     /*
  719.      * Extract the value of the desired pixel and format it as a string.
  720.      */
  721.  
  722.     pixelPtr = masterPtr->pix24 + (y * masterPtr->width + x) * 3;
  723.     sprintf(string, "%d %d %d", pixelPtr[0], pixelPtr[1],
  724.         pixelPtr[2]);
  725.     Tcl_AppendResult(interp, string, (char *) NULL);
  726.     } else if ((c == 'p') && (strncmp(argv[1], "put", length) == 0)) {
  727.     /*
  728.      * photo put command - first parse the options and colors specified.
  729.      */
  730.  
  731.     index = 2;
  732.     memset((VOID *) &options, 0, sizeof(options));
  733.     options.name = NULL;
  734.     if (ParseSubcommandOptions(&options, interp, OPT_TO,
  735.            &index, argc, argv) != TCL_OK) {
  736.         return TCL_ERROR;
  737.     }
  738.     if ((options.name == NULL) || (index < argc)) {
  739.         Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  740.              " put {{colors...}...} ?-to x1 y1 x2 y2?\"",
  741.              (char *) NULL);
  742.         return TCL_ERROR;
  743.     }
  744.     if (Tcl_SplitList(interp, options.name, &dataHeight, &srcArgv)
  745.         != TCL_OK) {
  746.         return TCL_ERROR;
  747.     }
  748.     tkwin = Tk_MainWindow(interp);
  749.     block.pixelPtr = NULL;
  750.     dataWidth = 0;
  751.     pixelPtr = NULL;
  752.     for (y = 0; y < dataHeight; ++y) {
  753.         if (Tcl_SplitList(interp, srcArgv[y], &listArgc, &listArgv)
  754.             != TCL_OK) {
  755.         break;
  756.         }
  757.         if (y == 0) {
  758.         dataWidth = listArgc;
  759.         pixelPtr = (unsigned char *) ckalloc((unsigned)
  760.             dataWidth * dataHeight * 3);
  761.         block.pixelPtr = pixelPtr;
  762.         } else {
  763.         if (listArgc != dataWidth) {
  764.             Tcl_AppendResult(interp, "all elements of color list must",
  765.                  " have the same number of elements",
  766.                 (char *) NULL);
  767.             ckfree((char *) listArgv);
  768.             break;
  769.         }
  770.         }
  771.         for (x = 0; x < dataWidth; ++x) {
  772.         if (!XParseColor(Tk_Display(tkwin), Tk_Colormap(tkwin),
  773.             listArgv[x], &color)) {
  774.             Tcl_AppendResult(interp, "can't parse color \"",
  775.                 listArgv[x], "\"", (char *) NULL);
  776.             break;
  777.         }
  778.         *pixelPtr++ = color.red >> 8;
  779.         *pixelPtr++ = color.green >> 8;
  780.         *pixelPtr++ = color.blue >> 8;
  781.         }
  782.         ckfree((char *) listArgv);
  783.         if (x < dataWidth)
  784.         break;
  785.     }
  786.     ckfree((char *) srcArgv);
  787.     if (y < dataHeight || dataHeight == 0 || dataWidth == 0) {
  788.         if (block.pixelPtr != NULL) {
  789.         ckfree((char *) block.pixelPtr);
  790.         }
  791.         if (y < dataHeight) {
  792.         return TCL_ERROR;
  793.         }
  794.         return TCL_OK;
  795.     }
  796.  
  797.     /*
  798.      * Fill in default values for the -to option, then
  799.      * copy the block in using Tk_PhotoPutBlock.
  800.      */
  801.  
  802.     if (((options.options & OPT_TO) == 0) || (options.toX2 < 0)) {
  803.         options.toX2 = options.toX + dataWidth;
  804.         options.toY2 = options.toY + dataHeight;
  805.     }
  806.     block.width = dataWidth;
  807.     block.height = dataHeight;
  808.     block.pitch = dataWidth * 3;
  809.     block.pixelSize = 3;
  810.     block.offset[0] = 0;
  811.     block.offset[1] = 1;
  812.     block.offset[2] = 2;
  813.     Tk_PhotoPutBlock((ClientData)masterPtr, &block,
  814.         options.toX, options.toY, options.toX2 - options.toX,
  815.         options.toY2 - options.toY);
  816.     ckfree((char *) block.pixelPtr);
  817.     } else if ((c == 'r') && (length >= 3)
  818.            && (strncmp(argv[1], "read", length) == 0)) {
  819.     /*
  820.      * photo read command - first parse the options specified.
  821.      */
  822.  
  823.     index = 2;
  824.     memset((VOID *) &options, 0, sizeof(options));
  825.     options.name = NULL;
  826.     options.format = NULL;
  827.     if (ParseSubcommandOptions(&options, interp,
  828.         OPT_FORMAT | OPT_FROM | OPT_TO | OPT_SHRINK,
  829.         &index, argc, argv) != TCL_OK) {
  830.         return TCL_ERROR;
  831.     }
  832.     if ((options.name == NULL) || (index < argc)) {
  833.         Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  834.             " read fileName ?-format format-name?",
  835.             " ?-from x1 y1 x2 y2? ?-to x y? ?-shrink?\"",
  836.             (char *) NULL);
  837.         return TCL_ERROR;
  838.     }
  839.  
  840.     /*
  841.      * Open the image file and look for a handler for it.
  842.      */
  843.  
  844.     realFileName = Tcl_TildeSubst(interp, options.name, &buffer);
  845.     if (realFileName == NULL) {
  846.         return TCL_ERROR;
  847.     }
  848.     f = fopen(realFileName, "rb");
  849.     Tcl_DStringFree(&buffer);
  850.     if (f == NULL) {
  851.         Tcl_AppendResult(interp, "couldn't read image file \"",
  852.             options.name, "\": ", Tcl_PosixError(interp),
  853.             (char *) NULL);
  854.         return TCL_ERROR;
  855.     }
  856.     if (MatchFileFormat(interp, f, options.name, options.format,
  857.         &imageFormat, &imageWidth, &imageHeight) != TCL_OK) {
  858.         fclose(f);
  859.         return TCL_ERROR;
  860.     }
  861.  
  862.     /*
  863.      * Check the values given for the -from option.
  864.      */
  865.  
  866.     if ((options.fromX > imageWidth) || (options.fromY > imageHeight)
  867.         || (options.fromX2 > imageWidth)
  868.         || (options.fromY2 > imageHeight)) {
  869.         Tcl_AppendResult(interp, "coordinates for -from option extend ",
  870.             "outside source image", (char *) NULL);
  871.         fclose(f);
  872.         return TCL_ERROR;
  873.     }
  874.     if (((options.options & OPT_FROM) == 0) || (options.fromX2 < 0)) {
  875.         width = imageWidth - options.fromX;
  876.         height = imageHeight - options.fromY;
  877.     } else {
  878.         width = options.fromX2 - options.fromX;
  879.         height = options.fromY2 - options.fromY;
  880.     }
  881.  
  882.     /*
  883.      * If the -shrink option was specified, set the size of the image.
  884.      */
  885.  
  886.     if (options.options & OPT_SHRINK) {
  887.         ImgPhotoSetSize(masterPtr, options.toX + width,
  888.             options.toY + height);
  889.     }
  890.  
  891.     /*
  892.      * Call the handler's file read procedure to read the data
  893.      * into the image.
  894.      */
  895.  
  896.     result = (*imageFormat->fileReadProc)(interp, f, options.name,
  897.         options.format, (Tk_PhotoHandle) masterPtr, options.toX,
  898.         options.toY, width, height, options.fromX, options.fromY);
  899.     if (f != NULL) {
  900.         fclose(f);
  901.     }
  902.     return result;
  903.     } else if ((c == 'r') && (length >= 3)
  904.            && (strncmp(argv[1], "redither", length) == 0)) {
  905.  
  906.     if (argc == 2) {
  907.         /*
  908.          * Call Dither if any part of the image is not correctly
  909.          * dithered at present.
  910.          */
  911.  
  912.         x = masterPtr->ditherX;
  913.         y = masterPtr->ditherY;
  914.         if (masterPtr->ditherX != 0) {
  915.         Dither(masterPtr, x, y, masterPtr->width - x, 1);
  916.         }
  917.         if (masterPtr->ditherY < masterPtr->height) {
  918.         x = 0;
  919.         Dither(masterPtr, 0, masterPtr->ditherY, masterPtr->width,
  920.             masterPtr->height - masterPtr->ditherY);
  921.         }
  922.  
  923.         if (y < masterPtr->height) {
  924.         /*
  925.          * Tell the core image code that part of the image has changed.
  926.          */
  927.  
  928.         Tk_ImageChanged(masterPtr->tkMaster, x, y,
  929.             (masterPtr->width - x), (masterPtr->height - y),
  930.             masterPtr->width, masterPtr->height);
  931.         }
  932.  
  933.     } else {
  934.         Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  935.             " redither\"", (char *) NULL);
  936.         return TCL_ERROR;
  937.     }
  938.     } else if ((c == 'w') && (strncmp(argv[1], "write", length) == 0)) {
  939.     /*
  940.      * photo write command - first parse and check any options given.
  941.      */
  942.  
  943.     index = 2;
  944.     memset((VOID *) &options, 0, sizeof(options));
  945.     options.name = NULL;
  946.     options.format = NULL;
  947.     if (ParseSubcommandOptions(&options, interp, OPT_FORMAT | OPT_FROM,
  948.         &index, argc, argv) != TCL_OK) {
  949.         return TCL_ERROR;
  950.     }
  951.     if ((options.name == NULL) || (index < argc)) {
  952.         Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
  953.             " write fileName ?-format format-name?",
  954.             "?-from x1 y1 x2 y2?\"", (char *) NULL);
  955.         return TCL_ERROR;
  956.     }
  957.     if ((options.fromX > masterPtr->width)
  958.         || (options.fromY > masterPtr->height)
  959.         || (options.fromX2 > masterPtr->width)
  960.         || (options.fromY2 > masterPtr->height)) {
  961.         Tcl_AppendResult(interp, "coordinates for -from option extend ",
  962.             "outside image", (char *) NULL);
  963.         return TCL_ERROR;
  964.     }
  965.  
  966.     /*
  967.      * Fill in default values for unspecified parameters.
  968.      */
  969.  
  970.     if (((options.options & OPT_FROM) == 0) || (options.fromX2 < 0)) {
  971.         options.fromX2 = masterPtr->width;
  972.         options.fromY2 = masterPtr->height;
  973.     }
  974.  
  975.     /*
  976.      * Search for an appropriate image file format handler,
  977.      * and give an error if none is found.
  978.      */
  979.  
  980.     matched = 0;
  981.     for (imageFormat = formatList; imageFormat != NULL;
  982.          imageFormat = imageFormat->nextPtr) {
  983.         if ((options.format == NULL)
  984.             || (strncasecmp(options.format, imageFormat->name,
  985.             strlen(imageFormat->name)) == 0)) {
  986.         matched = 1;
  987.         if (imageFormat->fileWriteProc != NULL) {
  988.             break;
  989.         }
  990.         }
  991.     }
  992.     if (imageFormat == NULL) {
  993.         if (options.format == NULL) {
  994.         Tcl_AppendResult(interp, "no available image file format ",
  995.             "has file writing capability", (char *) NULL);
  996.         } else if (!matched) {
  997.         Tcl_AppendResult(interp, "image file format \"",
  998.             options.format, "\" is unknown", (char *) NULL);
  999.         } else {
  1000.         Tcl_AppendResult(interp, "image file format \"",
  1001.             options.format, "\" has no file writing capability",
  1002.             (char *) NULL);
  1003.         }
  1004.         return TCL_ERROR;
  1005.     }
  1006.  
  1007.     /*
  1008.      * Call the handler's file write procedure to write out
  1009.      * the image.
  1010.      */
  1011.  
  1012.     Tk_PhotoGetImage((Tk_PhotoHandle) masterPtr, &block);
  1013.     block.pixelPtr += options.fromY * block.pitch + options.fromX * 3;
  1014.     block.width = options.fromX2 - options.fromX;
  1015.     block.height = options.fromY2 - options.fromY;
  1016.     return (*imageFormat->fileWriteProc)(interp, options.name,
  1017.         options.format, &block);
  1018.     } else {
  1019.     Tcl_AppendResult(interp, "bad option \"", argv[1],
  1020.         "\": must be blank, cget, configure, copy, get, put,",
  1021.         " read, redither, or write", (char *) NULL);
  1022.     return TCL_ERROR;
  1023.     }
  1024.  
  1025.     return TCL_OK;
  1026. }
  1027.  
  1028. /*
  1029.  *----------------------------------------------------------------------
  1030.  *
  1031.  * ParseSubcommandOptions --
  1032.  *
  1033.  *    This procedure is invoked to process one of the options
  1034.  *    which may be specified for the photo image subcommands,
  1035.  *    namely, -from, -to, -zoom, -subsample, -format, and -shrink.
  1036.  *
  1037.  * Results:
  1038.  *    A standard Tcl result.
  1039.  *
  1040.  * Side effects:
  1041.  *    Fields in *optPtr get filled in.
  1042.  *
  1043.  *----------------------------------------------------------------------
  1044.  */
  1045.  
  1046. static int
  1047. ParseSubcommandOptions(optPtr, interp, allowedOptions, optIndexPtr, argc, argv)
  1048.     struct SubcommandOptions *optPtr;
  1049.                 /* Information about the options specified
  1050.                  * and the values given is returned here. */
  1051.     Tcl_Interp *interp;        /* Interpreter to use for reporting errors. */
  1052.     int allowedOptions;        /* Indicates which options are valid for
  1053.                  * the current command. */
  1054.     int *optIndexPtr;        /* Points to a variable containing the
  1055.                  * current index in argv; this variable is
  1056.                  * updated by this procedure. */
  1057.     int argc;            /* Number of arguments in argv[]. */
  1058.     char **argv;        /* Arguments to be parsed. */
  1059. {
  1060.     int index, c, bit, currentBit;
  1061.     size_t length;
  1062.     char *option, **listPtr;
  1063.     int values[4];
  1064.     int numValues, maxValues, argIndex;
  1065.  
  1066.     for (index = *optIndexPtr; index < argc; *optIndexPtr = ++index) {
  1067.     /*
  1068.      * We can have one value specified without an option;
  1069.      * it goes into optPtr->name.
  1070.      */
  1071.  
  1072.     option = argv[index];
  1073.     if (option[0] != '-') {
  1074.         if (optPtr->name == NULL) {
  1075.         optPtr->name = option;
  1076.         continue;
  1077.         }
  1078.         break;
  1079.     }
  1080.  
  1081.     /*
  1082.      * Work out which option this is.
  1083.      */
  1084.  
  1085.     length = strlen(option);
  1086.     c = option[0];
  1087.     bit = 0;
  1088.     currentBit = 1;
  1089.     for (listPtr = optionNames; *listPtr != NULL; ++listPtr) {
  1090.         if ((c == *listPtr[0])
  1091.             && (strncmp(option, *listPtr, length) == 0)) {
  1092.         if (bit != 0) {
  1093.             bit = 0;    /* An ambiguous option. */
  1094.             break;
  1095.         }
  1096.         bit = currentBit;
  1097.         }
  1098.         currentBit <<= 1;
  1099.     }
  1100.  
  1101.     /*
  1102.      * If this option is not recognized and allowed, put
  1103.      * an error message in the interpreter and return.
  1104.      */
  1105.  
  1106.     if ((allowedOptions & bit) == 0) {
  1107.         Tcl_AppendResult(interp, "unrecognized option \"", argv[index],
  1108.             "\": must be ", (char *)NULL);
  1109.         bit = 1;
  1110.         for (listPtr = optionNames; *listPtr != NULL; ++listPtr) {
  1111.         if ((allowedOptions & bit) != 0) {
  1112.             if ((allowedOptions & (bit - 1)) != 0) {
  1113.             Tcl_AppendResult(interp, ", ", (char *) NULL);
  1114.             if ((allowedOptions & ~((bit << 1) - 1)) == 0) {
  1115.                 Tcl_AppendResult(interp, "or ", (char *) NULL);
  1116.             }
  1117.             }
  1118.             Tcl_AppendResult(interp, *listPtr, (char *) NULL);
  1119.         }
  1120.         bit <<= 1;
  1121.         }
  1122.         return TCL_ERROR;
  1123.     }
  1124.  
  1125.     /*
  1126.      * For the -from, -to, -zoom and -subsample options,
  1127.      * parse the values given.  Report an error if too few
  1128.      * or too many values are given.
  1129.      */
  1130.  
  1131.     if ((bit != OPT_SHRINK) && (bit != OPT_FORMAT)) {
  1132.         maxValues = ((bit == OPT_FROM) || (bit == OPT_TO))? 4: 2;
  1133.         argIndex = index + 1;
  1134.         for (numValues = 0; numValues < maxValues; ++numValues) {
  1135.         if ((argIndex < argc) && (isdigit(UCHAR(argv[argIndex][0]))
  1136.             || ((argv[argIndex][0] == '-')
  1137.             && (isdigit(UCHAR(argv[argIndex][1])))))) {
  1138.             if (Tcl_GetInt(interp, argv[argIndex], &values[numValues])
  1139.                 != TCL_OK) {
  1140.             return TCL_ERROR;
  1141.             }
  1142.         } else {
  1143.             break;
  1144.         }
  1145.         ++argIndex;
  1146.         }
  1147.  
  1148.         if (numValues == 0) {
  1149.         Tcl_AppendResult(interp, "the \"", argv[index], "\" option ",
  1150.              "requires one ", maxValues == 2? "or two": "to four",
  1151.              " integer values", (char *) NULL);
  1152.         return TCL_ERROR;
  1153.         }
  1154.         *optIndexPtr = (index += numValues);
  1155.  
  1156.         /*
  1157.          * Y values default to the corresponding X value if not specified.
  1158.          */
  1159.  
  1160.         if (numValues == 1) {
  1161.         values[1] = values[0];
  1162.         }
  1163.         if (numValues == 3) {
  1164.         values[3] = values[2];
  1165.         }
  1166.  
  1167.         /*
  1168.          * Check the values given and put them in the appropriate
  1169.          * field of the SubcommandOptions structure.
  1170.          */
  1171.  
  1172.         switch (bit) {
  1173.         case OPT_FROM:
  1174.             if ((values[0] < 0) || (values[1] < 0) || ((numValues > 2)
  1175.                 && ((values[2] < 0) || (values[3] < 0)))) {
  1176.             Tcl_AppendResult(interp, "value(s) for the -from",
  1177.                 " option must be non-negative", (char *) NULL);
  1178.             return TCL_ERROR;
  1179.             }
  1180.             if (numValues <= 2) {
  1181.             optPtr->fromX = values[0];
  1182.             optPtr->fromY = values[1];
  1183.             optPtr->fromX2 = -1;
  1184.             optPtr->fromY2 = -1;
  1185.             } else {
  1186.             optPtr->fromX = MIN(values[0], values[2]);
  1187.             optPtr->fromY = MIN(values[1], values[3]);
  1188.             optPtr->fromX2 = MAX(values[0], values[2]);
  1189.             optPtr->fromY2 = MAX(values[1], values[3]);
  1190.             }
  1191.             break;
  1192.         case OPT_SUBSAMPLE:
  1193.             optPtr->subsampleX = values[0];
  1194.             optPtr->subsampleY = values[1];
  1195.             break;
  1196.         case OPT_TO:
  1197.             if ((values[0] < 0) || (values[1] < 0) || ((numValues > 2)
  1198.                 && ((values[2] < 0) || (values[3] < 0)))) {
  1199.             Tcl_AppendResult(interp, "value(s) for the -to",
  1200.                 " option must be non-negative", (char *) NULL);
  1201.             return TCL_ERROR;
  1202.             }
  1203.             if (numValues <= 2) {
  1204.             optPtr->toX = values[0];
  1205.             optPtr->toY = values[1];
  1206.             optPtr->toX2 = -1;
  1207.             optPtr->toY2 = -1;
  1208.             } else {
  1209.             optPtr->toX = MIN(values[0], values[2]);
  1210.             optPtr->toY = MIN(values[1], values[3]);
  1211.             optPtr->toX2 = MAX(values[0], values[2]);
  1212.             optPtr->toY2 = MAX(values[1], values[3]);
  1213.             }
  1214.             break;
  1215.         case OPT_ZOOM:
  1216.             if ((values[0] <= 0) || (values[1] <= 0)) {
  1217.             Tcl_AppendResult(interp, "value(s) for the -zoom",
  1218.                 " option must be positive", (char *) NULL);
  1219.             return TCL_ERROR;
  1220.             }
  1221.             optPtr->zoomX = values[0];
  1222.             optPtr->zoomY = values[1];
  1223.             break;
  1224.         }
  1225.     } else if (bit == OPT_FORMAT) {
  1226.         /*
  1227.          * The -format option takes a single string value.
  1228.          */
  1229.  
  1230.         if (index + 1 < argc) {
  1231.         *optIndexPtr = ++index;
  1232.         optPtr->format = argv[index];
  1233.         } else {
  1234.         Tcl_AppendResult(interp, "the \"-format\" option ",
  1235.             "requires a value", (char *) NULL);
  1236.         return TCL_ERROR;
  1237.         }
  1238.     }
  1239.  
  1240.     /*
  1241.      * Remember that we saw this option.
  1242.      */
  1243.  
  1244.     optPtr->options |= bit;
  1245.     }
  1246.  
  1247.     return TCL_OK;
  1248. }
  1249.  
  1250. /*
  1251.  *----------------------------------------------------------------------
  1252.  *
  1253.  * ImgPhotoConfigureMaster --
  1254.  *
  1255.  *    This procedure is called when a photo image is created or
  1256.  *    reconfigured.  It processes configuration options and resets
  1257.  *    any instances of the image.
  1258.  *
  1259.  * Results:
  1260.  *    A standard Tcl return value.  If TCL_ERROR is returned then
  1261.  *    an error message is left in masterPtr->interp->result.
  1262.  *
  1263.  * Side effects:
  1264.  *    Existing instances of the image will be redisplayed to match
  1265.  *    the new configuration options.
  1266.  *
  1267.  *----------------------------------------------------------------------
  1268.  */
  1269.  
  1270. static int
  1271. ImgPhotoConfigureMaster(interp, masterPtr, argc, argv, flags)
  1272.     Tcl_Interp *interp;        /* Interpreter to use for reporting errors. */
  1273.     PhotoMaster *masterPtr;    /* Pointer to data structure describing
  1274.                  * overall photo image to (re)configure. */
  1275.     int argc;            /* Number of entries in argv. */
  1276.     char **argv;        /* Pairs of configuration options for image. */
  1277.     int flags;            /* Flags to pass to Tk_ConfigureWidget,
  1278.                  * such as TK_CONFIG_ARGV_ONLY. */
  1279. {
  1280.     PhotoInstance *instancePtr;
  1281.     char *oldFileString, *oldDataString, *realFileName;
  1282.     int result;
  1283.     FILE *f;
  1284.     Tk_PhotoImageFormat *imageFormat;
  1285.     int imageWidth, imageHeight;
  1286.     Tcl_DString buffer;
  1287.  
  1288.     /*
  1289.      * Save the current values for fileString and dataString, so we
  1290.      * can tell if the user specifies them anew.
  1291.      */
  1292.  
  1293.     oldFileString = masterPtr->fileString;
  1294.     oldDataString = (oldFileString == NULL)? masterPtr->dataString: NULL;
  1295.  
  1296.     /*
  1297.      * Process the configuration options specified.
  1298.      */
  1299.  
  1300.     if (Tk_ConfigureWidget(interp, Tk_MainWindow(interp), configSpecs,
  1301.         argc, argv, (char *) masterPtr, flags) != TCL_OK) {
  1302.     return TCL_ERROR;
  1303.     }
  1304.  
  1305.     /*
  1306.      * Regard the empty string for -file, -data or -format as the null
  1307.      * value.
  1308.      */
  1309.  
  1310.     if ((masterPtr->fileString != NULL) && (masterPtr->fileString[0] == 0)) {
  1311.     ckfree(masterPtr->fileString);
  1312.     masterPtr->fileString = NULL;
  1313.     }
  1314.     if ((masterPtr->dataString != NULL) && (masterPtr->dataString[0] == 0)) {
  1315.     ckfree(masterPtr->dataString);
  1316.     masterPtr->dataString = NULL;
  1317.     }
  1318.     if ((masterPtr->format != NULL) && (masterPtr->format[0] == 0)) {
  1319.     ckfree(masterPtr->format);
  1320.     masterPtr->format = NULL;
  1321.     }
  1322.  
  1323.     /*
  1324.      * Set the image to the user-requested size, if any,
  1325.      * and make sure storage is correctly allocated for this image.
  1326.      */
  1327.  
  1328.     ImgPhotoSetSize(masterPtr, masterPtr->width, masterPtr->height);
  1329.  
  1330.     /*
  1331.      * Read in the image from the file or string if the user has
  1332.      * specified the -file or -data option.
  1333.      */
  1334.  
  1335.     if ((masterPtr->fileString != NULL)
  1336.         && (masterPtr->fileString != oldFileString)) {
  1337.  
  1338.     realFileName = Tcl_TildeSubst(interp, masterPtr->fileString, &buffer);
  1339.     if (realFileName == NULL) {
  1340.         return TCL_ERROR;
  1341.     }
  1342.     f = fopen(realFileName, "rb");
  1343.     Tcl_DStringFree(&buffer);
  1344.     if (f == NULL) {
  1345.         Tcl_AppendResult(interp, "couldn't read image file \"",
  1346.             masterPtr->fileString, "\": ", Tcl_PosixError(interp),
  1347.             (char *) NULL);
  1348.         return TCL_ERROR;
  1349.     }
  1350.     if (MatchFileFormat(interp, f, masterPtr->fileString,
  1351.         masterPtr->format, &imageFormat, &imageWidth,
  1352.         &imageHeight) != TCL_OK) {
  1353.         fclose(f);
  1354.         return TCL_ERROR;
  1355.     }
  1356.     ImgPhotoSetSize(masterPtr, imageWidth, imageHeight);
  1357.     result = (*imageFormat->fileReadProc)(interp, f, masterPtr->fileString,
  1358.         masterPtr->format, (Tk_PhotoHandle) masterPtr, 0, 0,
  1359.         imageWidth, imageHeight, 0, 0);
  1360.     fclose(f);
  1361.     if (result != TCL_OK) {
  1362.         return TCL_ERROR;
  1363.     }
  1364.  
  1365.     masterPtr->flags |= IMAGE_CHANGED;
  1366.     }
  1367.  
  1368.     if ((masterPtr->fileString == NULL) && (masterPtr->dataString != NULL)
  1369.         && (masterPtr->dataString != oldDataString)) {
  1370.  
  1371.     if (MatchStringFormat(interp, masterPtr->dataString, 
  1372.         masterPtr->format, &imageFormat, &imageWidth,
  1373.         &imageHeight) != TCL_OK) {
  1374.         return TCL_ERROR;
  1375.     }
  1376.     ImgPhotoSetSize(masterPtr, imageWidth, imageHeight);
  1377.     if ((*imageFormat->stringReadProc)(interp, masterPtr->dataString,
  1378.         masterPtr->format, (Tk_PhotoHandle) masterPtr,
  1379.         0, 0, imageWidth, imageHeight, 0, 0) != TCL_OK) {
  1380.         return TCL_ERROR;
  1381.     }
  1382.  
  1383.     masterPtr->flags |= IMAGE_CHANGED;
  1384.     }
  1385.  
  1386.     /*
  1387.      * Enforce a reasonable value for gamma.
  1388.      */
  1389.  
  1390.     if (masterPtr->gamma <= 0) {
  1391.     masterPtr->gamma = 1.0;
  1392.     }
  1393.  
  1394.     /*
  1395.      * Cycle through all of the instances of this image, regenerating
  1396.      * the information for each instance.  Then force the image to be
  1397.      * redisplayed everywhere that it is used.
  1398.      */
  1399.  
  1400.     for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
  1401.         instancePtr = instancePtr->nextPtr) {
  1402.     ImgPhotoConfigureInstance(instancePtr);
  1403.     }
  1404.  
  1405.     /*
  1406.      * Inform the generic image code that the image
  1407.      * has (potentially) changed.
  1408.      */
  1409.  
  1410.     Tk_ImageChanged(masterPtr->tkMaster, 0, 0, masterPtr->width,
  1411.         masterPtr->height, masterPtr->width, masterPtr->height);
  1412.     masterPtr->flags &= ~IMAGE_CHANGED;
  1413.  
  1414.     return TCL_OK;
  1415. }
  1416.  
  1417. /*
  1418.  *----------------------------------------------------------------------
  1419.  *
  1420.  * ImgPhotoConfigureInstance --
  1421.  *
  1422.  *    This procedure is called to create displaying information for
  1423.  *    a photo image instance based on the configuration information
  1424.  *    in the master.  It is invoked both when new instances are
  1425.  *    created and when the master is reconfigured.
  1426.  *
  1427.  * Results:
  1428.  *    None.
  1429.  *
  1430.  * Side effects:
  1431.  *    Generates errors via Tk_BackgroundError if there are problems
  1432.  *    in setting up the instance.
  1433.  *
  1434.  *----------------------------------------------------------------------
  1435.  */
  1436.  
  1437. static void
  1438. ImgPhotoConfigureInstance(instancePtr)
  1439.     PhotoInstance *instancePtr;    /* Instance to reconfigure. */
  1440. {
  1441.     PhotoMaster *masterPtr = instancePtr->masterPtr;
  1442.     XImage *imagePtr;
  1443.     int bitsPerPixel;
  1444.     ColorTable *colorTablePtr;
  1445.     XRectangle validBox;
  1446.  
  1447.     /*
  1448.      * If the -palette configuration option has been set for the master,
  1449.      * use the value specified for our palette, but only if it is
  1450.      * a valid palette for our windows.  Use the gamma value specified
  1451.      * the master.
  1452.      */
  1453.  
  1454.     if ((masterPtr->palette && masterPtr->palette[0])
  1455.         && IsValidPalette(instancePtr, masterPtr->palette)) {
  1456.     instancePtr->palette = masterPtr->palette;
  1457.     } else {
  1458.     instancePtr->palette = instancePtr->defaultPalette;
  1459.     }
  1460.     instancePtr->gamma = masterPtr->gamma;
  1461.  
  1462.     /*
  1463.      * If we don't currently have a color table, or if the one we
  1464.      * have no longer applies (e.g. because our palette or gamma
  1465.      * has changed), get a new one.
  1466.      */
  1467.  
  1468.     colorTablePtr = instancePtr->colorTablePtr;
  1469.     if ((colorTablePtr == NULL)
  1470.         || (instancePtr->colormap != colorTablePtr->id.colormap)
  1471.         || (instancePtr->palette != colorTablePtr->id.palette)
  1472.         || (instancePtr->gamma != colorTablePtr->id.gamma)) {
  1473.     /*
  1474.      * Free up our old color table, and get a new one.
  1475.      */
  1476.  
  1477.     if (colorTablePtr != NULL) {
  1478.         colorTablePtr->liveRefCount -= 1;
  1479.         FreeColorTable(colorTablePtr);
  1480.     }
  1481.     GetColorTable(instancePtr);
  1482.  
  1483.     /*
  1484.      * Create a new XImage structure for sending data to
  1485.      * the X server, if necessary.
  1486.      */
  1487.  
  1488.     if (instancePtr->colorTablePtr->flags & BLACK_AND_WHITE) {
  1489.         bitsPerPixel = 1;
  1490.     } else {
  1491.         bitsPerPixel = instancePtr->visualInfo.depth;
  1492.     }
  1493.  
  1494.     if ((instancePtr->imagePtr == NULL)
  1495.         || (instancePtr->imagePtr->bits_per_pixel != bitsPerPixel)) {
  1496.         if (instancePtr->imagePtr != NULL) {
  1497.         XFree((char *) instancePtr->imagePtr);
  1498.         }
  1499.         imagePtr = XCreateImage(instancePtr->display,
  1500.             instancePtr->visualInfo.visual, (unsigned) bitsPerPixel,
  1501.             (bitsPerPixel > 1? ZPixmap: XYBitmap), 0, (char *) NULL,
  1502.             1, 1, 32, 0);
  1503.         instancePtr->imagePtr = imagePtr;
  1504.  
  1505.         /*
  1506.          * Determine the endianness of this machine.
  1507.          * We create images using the local host's endianness, rather
  1508.          * than the endianness of the server; otherwise we would have
  1509.          * to byte-swap any 16 or 32 bit values that we store in the
  1510.          * image in those situations where the server's endianness
  1511.          * is different from ours.
  1512.          */
  1513.  
  1514.         if (imagePtr != NULL) {
  1515.         union {
  1516.             int i;
  1517.             char c[sizeof(int)];
  1518.         } kludge;
  1519.  
  1520.         imagePtr->bitmap_unit = sizeof(pixel) * NBBY;
  1521.         kludge.i = 0;
  1522.         kludge.c[0] = 1;
  1523.         imagePtr->byte_order = (kludge.i == 1) ? LSBFirst : MSBFirst;
  1524.         _XInitImageFuncPtrs(imagePtr);
  1525.         }
  1526.     }
  1527.     }
  1528.  
  1529.     /*
  1530.      * If the user has specified a width and/or height for the master
  1531.      * which is different from our current width/height, set the size
  1532.      * to the values specified by the user.  If we have no pixmap, we
  1533.      * do this also, since it has the side effect of allocating a
  1534.      * pixmap for us.
  1535.      */
  1536.  
  1537.     if ((instancePtr->pixels == None) || (instancePtr->error == NULL)
  1538.         || (instancePtr->width != masterPtr->width)
  1539.         || (instancePtr->height != masterPtr->height)) {
  1540.     ImgPhotoInstanceSetSize(instancePtr);
  1541.     }
  1542.  
  1543.     /*
  1544.      * Redither this instance if necessary.
  1545.      */
  1546.  
  1547.     if ((masterPtr->flags & IMAGE_CHANGED)
  1548.         || (instancePtr->colorTablePtr != colorTablePtr)) {
  1549.     XClipBox(masterPtr->validRegion, &validBox);
  1550.     if ((validBox.width > 0) && (validBox.height > 0)) {
  1551.         DitherInstance(instancePtr, validBox.x, validBox.y,
  1552.             validBox.width, validBox.height);
  1553.     }
  1554.     }
  1555.  
  1556. }
  1557.  
  1558. /*
  1559.  *----------------------------------------------------------------------
  1560.  *
  1561.  * ImgPhotoGet --
  1562.  *
  1563.  *    This procedure is called for each use of a photo image in a
  1564.  *    widget.
  1565.  *
  1566.  * Results:
  1567.  *    The return value is a token for the instance, which is passed
  1568.  *    back to us in calls to ImgPhotoDisplay and ImgPhotoFree.
  1569.  *
  1570.  * Side effects:
  1571.  *    A data structure is set up for the instance (or, an existing
  1572.  *    instance is re-used for the new one).
  1573.  *
  1574.  *----------------------------------------------------------------------
  1575.  */
  1576.  
  1577. static ClientData
  1578. ImgPhotoGet(tkwin, masterData)
  1579.     Tk_Window tkwin;        /* Window in which the instance will be
  1580.                  * used. */
  1581.     ClientData masterData;    /* Pointer to our master structure for the
  1582.                  * image. */
  1583. {
  1584.     PhotoMaster *masterPtr = (PhotoMaster *) masterData;
  1585.     PhotoInstance *instancePtr;
  1586.     Colormap colormap;
  1587.     int mono, nRed, nGreen, nBlue;
  1588.     XVisualInfo visualInfo, *visInfoPtr;
  1589.     XRectangle validBox;
  1590.     char buf[16];
  1591.     int numVisuals;
  1592.     XColor *white, *black;
  1593.     XGCValues gcValues;
  1594.  
  1595.     /*
  1596.      * Table of "best" choices for palette for PseudoColor displays
  1597.      * with between 3 and 15 bits/pixel.
  1598.      */
  1599.  
  1600.     static int paletteChoice[13][3] = {
  1601.     /*  #red, #green, #blue */
  1602.      {2,  2,  2,            /* 3 bits, 8 colors */},
  1603.      {2,  3,  2,            /* 4 bits, 12 colors */},
  1604.      {3,  4,  2,            /* 5 bits, 24 colors */},
  1605.      {4,  5,  3,            /* 6 bits, 60 colors */},
  1606.      {5,  6,  4,            /* 7 bits, 120 colors */},
  1607.      {7,  7,  4,            /* 8 bits, 198 colors */},
  1608.      {8, 10,  6,            /* 9 bits, 480 colors */},
  1609.     {10, 12,  8,            /* 10 bits, 960 colors */},
  1610.     {14, 15,  9,            /* 11 bits, 1890 colors */},
  1611.     {16, 20, 12,            /* 12 bits, 3840 colors */},
  1612.     {20, 24, 16,            /* 13 bits, 7680 colors */},
  1613.     {26, 30, 20,            /* 14 bits, 15600 colors */},
  1614.     {32, 32, 30,            /* 15 bits, 30720 colors */}
  1615.     };
  1616.  
  1617.     /*
  1618.      * See if there is already an instance for windows using
  1619.      * the same colormap.  If so then just re-use it.
  1620.      */
  1621.  
  1622.     colormap = Tk_Colormap(tkwin);
  1623.     for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
  1624.         instancePtr = instancePtr->nextPtr) {
  1625.     if ((colormap == instancePtr->colormap)
  1626.         && (Tk_Display(tkwin) == instancePtr->display)) {
  1627.  
  1628.         /*
  1629.          * Re-use this instance.
  1630.          */
  1631.  
  1632.         if (instancePtr->refCount == 0) {
  1633.         /*
  1634.          * We are resurrecting this instance.
  1635.          */
  1636.  
  1637.         Tk_CancelIdleCall(DisposeInstance, (ClientData) instancePtr);
  1638.         if (instancePtr->colorTablePtr != NULL) {
  1639.             FreeColorTable(instancePtr->colorTablePtr);
  1640.         }
  1641.         GetColorTable(instancePtr);
  1642.         }
  1643.         instancePtr->refCount++;
  1644.         return (ClientData) instancePtr;
  1645.     }
  1646.     }
  1647.  
  1648.     /*
  1649.      * The image isn't already in use in a window with the same colormap.
  1650.      * Make a new instance of the image.
  1651.      */
  1652.  
  1653.     instancePtr = (PhotoInstance *) ckalloc(sizeof(PhotoInstance));
  1654.     instancePtr->masterPtr = masterPtr;
  1655.     instancePtr->display = Tk_Display(tkwin);
  1656.     instancePtr->colormap = Tk_Colormap(tkwin);
  1657.     instancePtr->refCount = 1;
  1658.     instancePtr->colorTablePtr = NULL;
  1659.     instancePtr->pixels = None;
  1660.     instancePtr->error = NULL;
  1661.     instancePtr->width = 0;
  1662.     instancePtr->height = 0;
  1663.     instancePtr->imagePtr = 0;
  1664.     instancePtr->nextPtr = masterPtr->instancePtr;
  1665.     masterPtr->instancePtr = instancePtr;
  1666.  
  1667.     /*
  1668.      * Obtain information about the visual and decide on the
  1669.      * default palette.
  1670.      */
  1671.  
  1672.     visualInfo.screen = Tk_ScreenNumber(tkwin);
  1673.     visualInfo.visualid = XVisualIDFromVisual(Tk_Visual(tkwin));
  1674.     visInfoPtr = XGetVisualInfo(Tk_Display(tkwin),
  1675.         VisualScreenMask | VisualIDMask, &visualInfo, &numVisuals);
  1676.     nRed = 2;
  1677.     nGreen = nBlue = 0;
  1678.     mono = 1;
  1679.     if (visInfoPtr != NULL) {
  1680.     instancePtr->visualInfo = *visInfoPtr;
  1681.     switch (visInfoPtr->class) {
  1682.         case DirectColor:
  1683.         case TrueColor:
  1684.         nRed = 1 << CountBits(visInfoPtr->red_mask);
  1685.         nGreen = 1 << CountBits(visInfoPtr->green_mask);
  1686.         nBlue = 1 << CountBits(visInfoPtr->blue_mask);
  1687.         mono = 0;
  1688.         break;
  1689.         case PseudoColor:
  1690.         case StaticColor:
  1691.         if (visInfoPtr->depth > 15) {
  1692.             nRed = 32;
  1693.             nGreen = 32;
  1694.             nBlue = 32;
  1695.             mono = 0;
  1696.         } else if (visInfoPtr->depth >= 3) {
  1697.             int *ip = paletteChoice[visInfoPtr->depth - 3];
  1698.     
  1699.             nRed = ip[0];
  1700.             nGreen = ip[1];
  1701.             nBlue = ip[2];
  1702.             mono = 0;
  1703.         }
  1704.         break;
  1705.         case GrayScale:
  1706.         case StaticGray:
  1707.         nRed = 1 << visInfoPtr->depth;
  1708.         break;
  1709.     }
  1710.     XFree((char *) visInfoPtr);
  1711.  
  1712.     } else {
  1713.     panic("ImgPhotoGet couldn't find visual for window");
  1714.     }
  1715.  
  1716.     sprintf(buf, ((mono) ? "%d": "%d/%d/%d"), nRed, nGreen, nBlue);
  1717.     instancePtr->defaultPalette = Tk_GetUid(buf);
  1718.  
  1719.     /*
  1720.      * Make a GC with background = black and foreground = white.
  1721.      */
  1722.  
  1723.     white = Tk_GetColor(masterPtr->interp, tkwin, "white");
  1724.     black = Tk_GetColor(masterPtr->interp, tkwin, "black");
  1725.     gcValues.foreground = (white != NULL)? white->pixel:
  1726.         WhitePixelOfScreen(Tk_Screen(tkwin));
  1727.     gcValues.background = (black != NULL)? black->pixel:
  1728.         BlackPixelOfScreen(Tk_Screen(tkwin));
  1729.     gcValues.graphics_exposures = False;
  1730.     instancePtr->gc = Tk_GetGC(tkwin,
  1731.         GCForeground|GCBackground|GCGraphicsExposures, &gcValues);
  1732.  
  1733.     /*
  1734.      * Set configuration options and finish the initialization of the instance.
  1735.      */
  1736.  
  1737.     ImgPhotoConfigureInstance(instancePtr);
  1738.  
  1739.     /*
  1740.      * If this is the first instance, must set the size of the image.
  1741.      */
  1742.  
  1743.     if (instancePtr->nextPtr == NULL) {
  1744.     Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0,
  1745.         masterPtr->width, masterPtr->height);
  1746.     }
  1747.  
  1748.     /*
  1749.      * Dither the image to fill in this instance's pixmap.
  1750.      */
  1751.  
  1752.     XClipBox(masterPtr->validRegion, &validBox);
  1753.     if ((validBox.width > 0) && (validBox.height > 0)) {
  1754.     DitherInstance(instancePtr, validBox.x, validBox.y, validBox.width,
  1755.         validBox.height);
  1756.     }
  1757.  
  1758.     return (ClientData) instancePtr;
  1759. }
  1760.  
  1761. /*
  1762.  *----------------------------------------------------------------------
  1763.  *
  1764.  * ImgPhotoDisplay --
  1765.  *
  1766.  *    This procedure is invoked to draw a photo image.
  1767.  *
  1768.  * Results:
  1769.  *    None.
  1770.  *
  1771.  * Side effects:
  1772.  *    A portion of the image gets rendered in a pixmap or window.
  1773.  *
  1774.  *----------------------------------------------------------------------
  1775.  */
  1776.  
  1777. static void
  1778. ImgPhotoDisplay(clientData, display, drawable, imageX, imageY, width,
  1779.     height, drawableX, drawableY)
  1780.     ClientData clientData;    /* Pointer to PhotoInstance structure for
  1781.                  * for instance to be displayed. */
  1782.     Display *display;        /* Display on which to draw image. */
  1783.     Drawable drawable;        /* Pixmap or window in which to draw image. */
  1784.     int imageX, imageY;        /* Upper-left corner of region within image
  1785.                  * to draw. */
  1786.     int width, height;        /* Dimensions of region within image to draw. */
  1787.     int drawableX, drawableY;    /* Coordinates within drawable that
  1788.                  * correspond to imageX and imageY. */
  1789. {
  1790.     PhotoInstance *instancePtr = (PhotoInstance *) clientData;
  1791.  
  1792.     /*
  1793.      * If there's no pixmap, it means that an error occurred
  1794.      * while creating the image instance so it can't be displayed.
  1795.      */
  1796.  
  1797.     if (instancePtr->pixels == None) {
  1798.     return;
  1799.     }
  1800.  
  1801.     /*
  1802.      * masterPtr->region describes which parts of the image contain
  1803.      * valid data.  We set this region as the clip mask for the gc,
  1804.      * setting its origin appropriately, and use it when drawing the
  1805.      * image.
  1806.      */
  1807.  
  1808.     XSetRegion(display, instancePtr->gc, instancePtr->masterPtr->validRegion);
  1809.     XSetClipOrigin(display, instancePtr->gc, drawableX - imageX,
  1810.         drawableY - imageY);
  1811.     XCopyArea(display, instancePtr->pixels, drawable, instancePtr->gc,
  1812.         imageX, imageY, (unsigned) width, (unsigned) height,
  1813.         drawableX, drawableY);
  1814.     XSetClipMask(display, instancePtr->gc, None);
  1815.     XSetClipOrigin(display, instancePtr->gc, 0, 0);
  1816. }
  1817.  
  1818. /*
  1819.  *----------------------------------------------------------------------
  1820.  *
  1821.  * ImgPhotoFree --
  1822.  *
  1823.  *    This procedure is called when a widget ceases to use a
  1824.  *    particular instance of an image.  We don't actually get
  1825.  *    rid of the instance until later because we may be about
  1826.  *    to get this instance again.
  1827.  *
  1828.  * Results:
  1829.  *    None.
  1830.  *
  1831.  * Side effects:
  1832.  *    Internal data structures get cleaned up, later.
  1833.  *
  1834.  *----------------------------------------------------------------------
  1835.  */
  1836.  
  1837. static void
  1838. ImgPhotoFree(clientData, display)
  1839.     ClientData clientData;    /* Pointer to PhotoInstance structure for
  1840.                  * for instance to be displayed. */
  1841.     Display *display;        /* Display containing window that used image. */
  1842. {
  1843.     PhotoInstance *instancePtr = (PhotoInstance *) clientData;
  1844.     ColorTable *colorPtr;
  1845.  
  1846.     instancePtr->refCount -= 1;
  1847.     if (instancePtr->refCount > 0) {
  1848.     return;
  1849.     }
  1850.  
  1851.     /*
  1852.      * There are no more uses of the image within this widget.
  1853.      * Decrement the count of live uses of its color table, so
  1854.      * that its colors can be reclaimed if necessary, and
  1855.      * set up an idle call to free the instance structure.
  1856.      */
  1857.  
  1858.     colorPtr = instancePtr->colorTablePtr;
  1859.     if (colorPtr != NULL) {
  1860.     colorPtr->liveRefCount -= 1;
  1861.     }
  1862.     
  1863.     Tk_DoWhenIdle(DisposeInstance, (ClientData) instancePtr);
  1864. }
  1865.  
  1866. /*
  1867.  *----------------------------------------------------------------------
  1868.  *
  1869.  * ImgPhotoDelete --
  1870.  *
  1871.  *    This procedure is called by the image code to delete the
  1872.  *    master structure for an image.
  1873.  *
  1874.  * Results:
  1875.  *    None.
  1876.  *
  1877.  * Side effects:
  1878.  *    Resources associated with the image get freed.
  1879.  *
  1880.  *----------------------------------------------------------------------
  1881.  */
  1882.  
  1883. static void
  1884. ImgPhotoDelete(masterData)
  1885.     ClientData masterData;    /* Pointer to PhotoMaster structure for
  1886.                  * image.  Must not have any more instances. */
  1887. {
  1888.     PhotoMaster *masterPtr = (PhotoMaster *) masterData;
  1889.     PhotoInstance *instancePtr;
  1890.  
  1891.     while ((instancePtr = masterPtr->instancePtr) != NULL) {
  1892.     if (instancePtr->refCount > 0) {
  1893.         panic("tried to delete photo image when instances still exist");
  1894.     }
  1895.     Tk_CancelIdleCall(DisposeInstance, (ClientData) instancePtr);
  1896.     DisposeInstance((ClientData) instancePtr);
  1897.     }
  1898.     masterPtr->tkMaster = NULL;
  1899.     if (masterPtr->imageCmd != NULL) {
  1900.     Tcl_DeleteCommand(masterPtr->interp,
  1901.         Tcl_GetCommandName(masterPtr->interp, masterPtr->imageCmd));
  1902.     }
  1903.     if (masterPtr->pix24 != NULL) {
  1904.     ckfree((char *) masterPtr->pix24);
  1905.     }
  1906.     if (masterPtr->validRegion != NULL) {
  1907.     XDestroyRegion(masterPtr->validRegion);
  1908.     }
  1909.     Tk_FreeOptions(configSpecs, (char *) masterPtr, (Display *) NULL, 0);
  1910.     ckfree((char *) masterPtr);
  1911. }
  1912.  
  1913. /*
  1914.  *----------------------------------------------------------------------
  1915.  *
  1916.  * ImgPhotoCmdDeletedProc --
  1917.  *
  1918.  *    This procedure is invoked when the image command for an image
  1919.  *    is deleted.  It deletes the image.
  1920.  *
  1921.  * Results:
  1922.  *    None.
  1923.  *
  1924.  * Side effects:
  1925.  *    The image is deleted.
  1926.  *
  1927.  *----------------------------------------------------------------------
  1928.  */
  1929.  
  1930. static void
  1931. ImgPhotoCmdDeletedProc(clientData)
  1932.     ClientData clientData;    /* Pointer to PhotoMaster structure for
  1933.                  * image. */
  1934. {
  1935.     PhotoMaster *masterPtr = (PhotoMaster *) clientData;
  1936.  
  1937.     masterPtr->imageCmd = NULL;
  1938.     if (masterPtr->tkMaster != NULL) {
  1939.     Tk_DeleteImage(masterPtr->interp, Tk_NameOfImage(masterPtr->tkMaster));
  1940.     }
  1941. }
  1942.  
  1943. /*
  1944.  *----------------------------------------------------------------------
  1945.  *
  1946.  * ImgPhotoSetSize --
  1947.  *
  1948.  *    This procedure reallocates the image storage and instance
  1949.  *    pixmaps for a photo image, as necessary, to change the
  1950.  *    image's size to `width' x `height' pixels.
  1951.  *
  1952.  * Results:
  1953.  *    None.
  1954.  *
  1955.  * Side effects:
  1956.  *    Storage gets reallocated, for the master and all its instances.
  1957.  *
  1958.  *----------------------------------------------------------------------
  1959.  */
  1960.  
  1961. static void
  1962. ImgPhotoSetSize(masterPtr, width, height)
  1963.     PhotoMaster *masterPtr;
  1964.     int width, height;
  1965. {
  1966.     unsigned char *newPix24;
  1967.     int h, offset, pitch;
  1968.     unsigned char *srcPtr, *destPtr;
  1969.     XRectangle validBox, clipBox;
  1970.     Region clipRegion;
  1971.     PhotoInstance *instancePtr;
  1972.  
  1973.     if (masterPtr->userWidth > 0) {
  1974.     width = masterPtr->userWidth;
  1975.     }
  1976.     if (masterPtr->userHeight > 0) {
  1977.     height = masterPtr->userHeight;
  1978.     }
  1979.  
  1980.     /*
  1981.      * We have to trim the valid region if it is currently
  1982.      * larger than the new image size.
  1983.      */
  1984.  
  1985.     XClipBox(masterPtr->validRegion, &validBox);
  1986.     if ((validBox.x + validBox.width > (unsigned) width)
  1987.         || (validBox.y + validBox.height > (unsigned) height)) {
  1988.     clipBox.x = 0;
  1989.     clipBox.y = 0;
  1990.     clipBox.width = width;
  1991.     clipBox.height = height;
  1992.     clipRegion = XCreateRegion();
  1993.     XUnionRectWithRegion(&clipBox, clipRegion, clipRegion);
  1994.     XIntersectRegion(masterPtr->validRegion, clipRegion,
  1995.         masterPtr->validRegion);
  1996.     XDestroyRegion(clipRegion);
  1997.     XClipBox(masterPtr->validRegion, &validBox);
  1998.     }
  1999.  
  2000.     if ((width != masterPtr->width) || (height != masterPtr->height)
  2001.         || (masterPtr->pix24 == NULL)) {
  2002.  
  2003.     /*
  2004.      * Reallocate storage for the 24-bit image and copy
  2005.      * over valid regions.
  2006.      */
  2007.  
  2008.     pitch = width * 3;
  2009.     newPix24 = (unsigned char *) ckalloc((unsigned) (height * pitch));
  2010.  
  2011.     /*
  2012.      * Zero the new array.  The dithering code shouldn't read the
  2013.      * areas outside validBox, but they might be copied to another
  2014.      * photo image or written to a file.
  2015.      */
  2016.  
  2017.     if ((masterPtr->pix24 != NULL)
  2018.         && ((width == masterPtr->width) || (width == validBox.width))) {
  2019.         if (validBox.y > 0) {
  2020.         memset((VOID *) newPix24, 0, (size_t) (validBox.y * pitch));
  2021.         }
  2022.         h = validBox.y + validBox.height;
  2023.         if (h < height) {
  2024.         memset((VOID *) (newPix24 + h * pitch), 0,
  2025.             (size_t) ((height - h) * pitch));
  2026.         }
  2027.     } else {
  2028.         memset((VOID *) newPix24, 0, (size_t) (height * pitch));
  2029.     }
  2030.  
  2031.     if (masterPtr->pix24 != NULL) {
  2032.  
  2033.         /*
  2034.          * Copy the common area over to the new array array and
  2035.          * free the old array.
  2036.          */
  2037.  
  2038.         if (width == masterPtr->width) {
  2039.  
  2040.         /*
  2041.          * The region to be copied is contiguous.
  2042.          */
  2043.  
  2044.         offset = validBox.y * pitch;
  2045.         memcpy((VOID *) (newPix24 + offset),
  2046.             (VOID *) (masterPtr->pix24 + offset),
  2047.             (size_t) (validBox.height * pitch));
  2048.  
  2049.         } else if ((validBox.width > 0) && (validBox.height > 0)) {
  2050.  
  2051.         /*
  2052.          * Area to be copied is not contiguous - copy line by line.
  2053.          */
  2054.  
  2055.         destPtr = newPix24 + (validBox.y * width + validBox.x) * 3;
  2056.         srcPtr = masterPtr->pix24 + (validBox.y * masterPtr->width
  2057.             + validBox.x) * 3;
  2058.         for (h = validBox.height; h > 0; h--) {
  2059.             memcpy((VOID *) destPtr, (VOID *) srcPtr,
  2060.                 (size_t) (validBox.width * 3));
  2061.             destPtr += width * 3;
  2062.             srcPtr += masterPtr->width * 3;
  2063.         }
  2064.         }
  2065.  
  2066.         ckfree((char *) masterPtr->pix24);
  2067.     }
  2068.  
  2069.     masterPtr->pix24 = newPix24;
  2070.     masterPtr->width = width;
  2071.     masterPtr->height = height;
  2072.  
  2073.     /*
  2074.      * Dithering will be correct up to the end of the last
  2075.      * pre-existing complete scanline.
  2076.      */
  2077.  
  2078.     if ((validBox.x > 0) || (validBox.y > 0)) {
  2079.         masterPtr->ditherX = 0;
  2080.         masterPtr->ditherY = 0;
  2081.     } else if (validBox.width == width) {
  2082.         if ((int) validBox.height < masterPtr->ditherY) {
  2083.         masterPtr->ditherX = 0;
  2084.         masterPtr->ditherY = validBox.height;
  2085.         }
  2086.     } else {
  2087.         if ((masterPtr->ditherY > 0)
  2088.             || ((int) validBox.width < masterPtr->ditherX)) {
  2089.         masterPtr->ditherX = validBox.width;
  2090.         masterPtr->ditherY = 0;
  2091.         }
  2092.     }
  2093.     }
  2094.  
  2095.     /*
  2096.      * Now adjust the sizes of the pixmaps for all of the instances.
  2097.      */
  2098.  
  2099.     for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
  2100.         instancePtr = instancePtr->nextPtr) {
  2101.     ImgPhotoInstanceSetSize(instancePtr);
  2102.     }
  2103. }
  2104.  
  2105. /*
  2106.  *----------------------------------------------------------------------
  2107.  *
  2108.  * ImgPhotoInstanceSetSize --
  2109.  *
  2110.  *     This procedure reallocates the instance pixmap and dithering
  2111.  *    error array for a photo instance, as necessary, to change the
  2112.  *    image's size to `width' x `height' pixels.
  2113.  *
  2114.  * Results:
  2115.  *    None.
  2116.  *
  2117.  * Side effects:
  2118.  *    Storage gets reallocated, here and in the X server.
  2119.  *
  2120.  *----------------------------------------------------------------------
  2121.  */
  2122.  
  2123. static void
  2124. ImgPhotoInstanceSetSize(instancePtr)
  2125.     PhotoInstance *instancePtr;        /* Instance whose size is to be
  2126.                      * changed. */
  2127. {
  2128.     PhotoMaster *masterPtr;
  2129.     schar *newError;
  2130.     schar *errSrcPtr, *errDestPtr;
  2131.     int h, offset, pitch;
  2132.     XRectangle validBox;
  2133.     Pixmap newPixmap;
  2134.  
  2135.     masterPtr = instancePtr->masterPtr;
  2136.     XClipBox(masterPtr->validRegion, &validBox);
  2137.  
  2138.     if ((instancePtr->width != masterPtr->width)
  2139.         || (instancePtr->height != masterPtr->height)
  2140.         || (instancePtr->pixels == None)) {
  2141.     newPixmap = Tk_GetPixmap(instancePtr->display,
  2142.         RootWindow(instancePtr->display,
  2143.             instancePtr->visualInfo.screen),
  2144.         (masterPtr->width > 0) ? masterPtr->width: 1,
  2145.         (masterPtr->height > 0) ? masterPtr->height: 1,
  2146.         instancePtr->visualInfo.depth);
  2147.  
  2148.     if (instancePtr->pixels != None) {
  2149.         /*
  2150.          * Copy any common pixels from the old pixmap and free it.
  2151.          */
  2152.         XCopyArea(instancePtr->display, instancePtr->pixels, newPixmap,
  2153.             instancePtr->gc, validBox.x, validBox.y,
  2154.             validBox.width, validBox.height, validBox.x, validBox.y);
  2155.         Tk_FreePixmap(instancePtr->display, instancePtr->pixels);
  2156.     }
  2157.     instancePtr->pixels = newPixmap;
  2158.     }
  2159.  
  2160.     if ((instancePtr->width != masterPtr->width)
  2161.         || (instancePtr->height != masterPtr->height)
  2162.         || (instancePtr->error == NULL)) {
  2163.  
  2164.     pitch = masterPtr->width * sizeof(schar) * 3;
  2165.     newError = (schar *) ckalloc((unsigned) (masterPtr->height * pitch));
  2166.  
  2167.     /*
  2168.      * Zero the new array so that we don't get bogus error values
  2169.      * propagating into areas we dither later.
  2170.      */
  2171.  
  2172.     if ((instancePtr->error != NULL)
  2173.         && ((instancePtr->width == masterPtr->width)
  2174.         || (validBox.width == masterPtr->width))) {
  2175.         if (validBox.y > 0) {
  2176.         memset((VOID *) newError, 0, (size_t) (validBox.y * pitch));
  2177.         }
  2178.         h = validBox.y + validBox.height;
  2179.         if (h < masterPtr->height) {
  2180.         memset((VOID *) (newError + h * pitch), 0,
  2181.             (size_t) ((masterPtr->height - h) * pitch));
  2182.         }
  2183.     } else {
  2184.         memset((VOID *) newError, 0, (size_t) (masterPtr->height * pitch));
  2185.     }
  2186.  
  2187.     if (instancePtr->error != NULL) {
  2188.  
  2189.         /*
  2190.          * Copy the common area over to the new array
  2191.          * and free the old array.
  2192.          */
  2193.  
  2194.         if (masterPtr->width == instancePtr->width) {
  2195.  
  2196.         offset = validBox.y * pitch;
  2197.         memcpy((VOID *) (newError + offset),
  2198.             (VOID *) (instancePtr->error + offset),
  2199.             (size_t) (validBox.height * pitch));
  2200.  
  2201.         } else if (validBox.width > 0 && validBox.height > 0) {
  2202.  
  2203.         errDestPtr = newError
  2204.             + validBox.y * pitch + validBox.x * 3 * sizeof(schar);
  2205.         errSrcPtr = instancePtr->error
  2206.             + (validBox.y * instancePtr->width + validBox.x)
  2207.             * 3 * sizeof(schar);
  2208.         for (h = validBox.height; h > 0; --h) {
  2209.             memcpy((VOID *) errDestPtr, (VOID *) errSrcPtr,
  2210.                 validBox.width * 3 * sizeof(schar));
  2211.             errDestPtr += masterPtr->width * 3 * sizeof(schar);
  2212.             errSrcPtr += instancePtr->width * 3 * sizeof(schar);
  2213.         }
  2214.         }
  2215.         ckfree((char *) instancePtr->error);
  2216.     }
  2217.  
  2218.     instancePtr->error = newError;
  2219.     }
  2220.  
  2221.     instancePtr->width = masterPtr->width;
  2222.     instancePtr->height = masterPtr->height;
  2223. }
  2224.  
  2225. /*
  2226.  *----------------------------------------------------------------------
  2227.  *
  2228.  * IsValidPalette --
  2229.  *
  2230.  *    This procedure is called to check whether a value given for
  2231.  *    the -palette option is valid for a particular instance
  2232.  *     of a photo image.
  2233.  *
  2234.  * Results:
  2235.  *    A boolean value: 1 if the palette is acceptable, 0 otherwise.
  2236.  *
  2237.  * Side effects:
  2238.  *    None.
  2239.  *
  2240.  *----------------------------------------------------------------------
  2241.  */
  2242.  
  2243. static int
  2244. IsValidPalette(instancePtr, palette)
  2245.     PhotoInstance *instancePtr;        /* Instance to which the palette
  2246.                      * specification is to be applied. */
  2247.     char *palette;            /* Palette specification string. */
  2248. {
  2249.     int nRed, nGreen, nBlue, mono, numColors;
  2250.     char *endp;
  2251.  
  2252.     /*
  2253.      * First parse the specification: it must be of the form
  2254.      * %d or %d/%d/%d.
  2255.      */
  2256.  
  2257.     nRed = strtol(palette, &endp, 10);
  2258.     if ((endp == palette) || ((*endp != 0) && (*endp != '/'))
  2259.         || (nRed < 2) || (nRed > 256)) {
  2260.     return 0;
  2261.     }
  2262.  
  2263.     if (*endp == 0) {
  2264.     mono = 1;
  2265.     nGreen = nBlue = nRed;
  2266.     } else {
  2267.     palette = endp + 1;
  2268.     nGreen = strtol(palette, &endp, 10);
  2269.     if ((endp == palette) || (*endp != '/') || (nGreen < 2)
  2270.         || (nGreen > 256)) {
  2271.         return 0;
  2272.     }
  2273.     palette = endp + 1;
  2274.     nBlue = strtol(palette, &endp, 10);
  2275.     if ((endp == palette) || (*endp != 0) || (nBlue < 2)
  2276.         || (nBlue > 256)) {
  2277.         return 0;
  2278.     }
  2279.     mono = 0;
  2280.     }
  2281.  
  2282.     switch (instancePtr->visualInfo.class) {
  2283.     case DirectColor:
  2284.     case TrueColor:
  2285.         if ((nRed > (1 << CountBits(instancePtr->visualInfo.red_mask)))
  2286.             || (nGreen > (1
  2287.             << CountBits(instancePtr->visualInfo.green_mask)))
  2288.             || (nBlue > (1
  2289.             << CountBits(instancePtr->visualInfo.blue_mask)))) {
  2290.         return 0;
  2291.         }
  2292.         break;
  2293.     case PseudoColor:
  2294.     case StaticColor:
  2295.         numColors = nRed;
  2296.         if (!mono) {
  2297.         numColors *= nGreen*nBlue;
  2298.         }
  2299.         if (numColors > (1 << instancePtr->visualInfo.depth)) {
  2300.         return 0;
  2301.         }
  2302.         break;
  2303.     case GrayScale:
  2304.     case StaticGray:
  2305.         if (!mono || (nRed > (1 << instancePtr->visualInfo.depth))) {
  2306.         return 0;
  2307.         }
  2308.         break;
  2309.     }
  2310.  
  2311.     return 1;
  2312. }
  2313.  
  2314. /*
  2315.  *----------------------------------------------------------------------
  2316.  *
  2317.  * CountBits --
  2318.  *
  2319.  *    This procedure counts how many bits are set to 1 in `mask'.
  2320.  *
  2321.  * Results:
  2322.  *    The integer number of bits.
  2323.  *
  2324.  * Side effects:
  2325.  *    None.
  2326.  *
  2327.  *----------------------------------------------------------------------
  2328.  */
  2329.  
  2330. static int
  2331. CountBits(mask)
  2332.     pixel mask;            /* Value to count the 1 bits in. */
  2333. {
  2334.     int n;
  2335.  
  2336.     for( n = 0; mask != 0; mask &= mask - 1 )
  2337.     n++;
  2338.     return n;
  2339. }
  2340.  
  2341. /*
  2342.  *----------------------------------------------------------------------
  2343.  *
  2344.  * GetColorTable --
  2345.  *
  2346.  *    This procedure is called to allocate a table of colormap
  2347.  *    information for an instance of a photo image.  Only one such
  2348.  *    table is allocated for all photo instances using the same
  2349.  *    display, colormap, palette and gamma values, so that the
  2350.  *    application need only request a set of colors from the X
  2351.  *    server once for all such photo widgets.  This procedure
  2352.  *    maintains a hash table to find previously-allocated
  2353.  *    ColorTables.
  2354.  *
  2355.  * Results:
  2356.  *    None.
  2357.  *
  2358.  * Side effects:
  2359.  *    A new ColorTable may be allocated and placed in the hash
  2360.  *    table, and have colors allocated for it.
  2361.  *
  2362.  *----------------------------------------------------------------------
  2363.  */
  2364.  
  2365. static void
  2366. GetColorTable(instancePtr)
  2367.     PhotoInstance *instancePtr;        /* Instance needing a color table. */
  2368. {
  2369.     ColorTable *colorPtr;
  2370.     Tcl_HashEntry *entry;
  2371.     ColorTableId id;
  2372.     int isNew;
  2373.  
  2374.     /*
  2375.      * Look for an existing ColorTable in the hash table.
  2376.      */
  2377.  
  2378.     memset((VOID *) &id, 0, sizeof(id));
  2379.     id.display = instancePtr->display;
  2380.     id.colormap = instancePtr->colormap;
  2381.     id.palette = instancePtr->palette;
  2382.     id.gamma = instancePtr->gamma;
  2383.     if (!imgPhotoColorHashInitialized) {
  2384.     Tcl_InitHashTable(&imgPhotoColorHash, N_COLOR_HASH);
  2385.     imgPhotoColorHashInitialized = 1;
  2386.     }
  2387.     entry = Tcl_CreateHashEntry(&imgPhotoColorHash, (char *) &id, &isNew);
  2388.  
  2389.     if (!isNew) {
  2390.     /*
  2391.      * Re-use the existing entry.
  2392.      */
  2393.  
  2394.     colorPtr = (ColorTable *) Tcl_GetHashValue(entry);
  2395.  
  2396.     } else {
  2397.     /*
  2398.      * No color table currently available; need to make one.
  2399.      */
  2400.  
  2401.     colorPtr = (ColorTable *) ckalloc(sizeof(ColorTable));
  2402.     colorPtr->id = id;
  2403.     colorPtr->flags = 0;
  2404.     colorPtr->refCount = 0;
  2405.     colorPtr->liveRefCount = 0;
  2406.     colorPtr->numColors = 0;
  2407.     colorPtr->visualInfo = instancePtr->visualInfo;
  2408.     colorPtr->pixelMap = NULL;
  2409.     Tcl_SetHashValue(entry, colorPtr);
  2410.     }
  2411.  
  2412.     colorPtr->refCount++;
  2413.     colorPtr->liveRefCount++;
  2414.     instancePtr->colorTablePtr = colorPtr;
  2415.     if (colorPtr->flags & DISPOSE_PENDING) {
  2416.     Tk_CancelIdleCall(DisposeColorTable, (ClientData) colorPtr);
  2417.     colorPtr->flags &= ~DISPOSE_PENDING;
  2418.     }
  2419.  
  2420.     /*
  2421.      * Allocate colors for this color table if necessary.
  2422.      */
  2423.  
  2424.     if ((colorPtr->numColors == 0)
  2425.         && ((colorPtr->flags & BLACK_AND_WHITE) == 0)) {
  2426.     AllocateColors(colorPtr);
  2427.     }
  2428. }
  2429.  
  2430. /*
  2431.  *----------------------------------------------------------------------
  2432.  *
  2433.  * FreeColorTable --
  2434.  *
  2435.  *    This procedure is called when an instance ceases using a
  2436.  *    color table.
  2437.  *
  2438.  * Results:
  2439.  *    None.
  2440.  *
  2441.  * Side effects:
  2442.  *    If no other instances are using this color table, a when-idle
  2443.  *    handler is registered to free up the color table and the colors
  2444.  *    allocated for it.
  2445.  *
  2446.  *----------------------------------------------------------------------
  2447.  */
  2448.  
  2449. static void
  2450. FreeColorTable(colorPtr)
  2451.     ColorTable *colorPtr;    /* Pointer to the color table which is
  2452.                  * no longer required by an instance. */
  2453. {
  2454.     colorPtr->refCount--;
  2455.     if (colorPtr->refCount > 0) {
  2456.     return;
  2457.     }
  2458.     if ((colorPtr->flags & DISPOSE_PENDING) == 0) {
  2459.     Tk_DoWhenIdle(DisposeColorTable, (ClientData) colorPtr);
  2460.     colorPtr->flags |= DISPOSE_PENDING;
  2461.     }
  2462. }
  2463.  
  2464. /*
  2465.  *----------------------------------------------------------------------
  2466.  *
  2467.  * AllocateColors --
  2468.  *
  2469.  *    This procedure allocates the colors required by a color table,
  2470.  *    and sets up the fields in the color table data structure which
  2471.  *    are used in dithering.
  2472.  *
  2473.  * Results:
  2474.  *    None.
  2475.  *
  2476.  * Side effects:
  2477.  *    Colors are allocated from the X server.  Fields in the
  2478.  *    color table data structure are updated.
  2479.  *
  2480.  *----------------------------------------------------------------------
  2481.  */
  2482.  
  2483. static void
  2484. AllocateColors(colorPtr)
  2485.     ColorTable *colorPtr;    /* Pointer to the color table requiring
  2486.                  * colors to be allocated. */
  2487. {
  2488.     int i, r, g, b, rMult, mono;
  2489.     int numColors, nRed, nGreen, nBlue;
  2490.     double fr, fg, fb, igam;
  2491.     XColor *colors;
  2492.     unsigned long *pixels;
  2493.  
  2494.     /* 16-bit intensity value for i/n of full intensity. */
  2495. #   define CFRAC(i, n)    ((i) * 65535 / (n))
  2496.  
  2497.     /* As for CFRAC, but apply exponent of g. */
  2498. #   define CGFRAC(i, n, g)    ((int)(65535 * pow((double)(i) / (n), (g))))
  2499.  
  2500.     /*
  2501.      * First parse the palette specification to get the required number of
  2502.      * shades of each primary.
  2503.      */
  2504.  
  2505.     mono = sscanf(colorPtr->id.palette, "%d/%d/%d", &nRed, &nGreen, &nBlue)
  2506.         <= 1;
  2507.     igam = 1.0 / colorPtr->id.gamma;
  2508.  
  2509.     /*
  2510.      * Each time around this loop, we reduce the number of colors we're
  2511.      * trying to allocate until we succeed in allocating all of the colors
  2512.      * we need.
  2513.      */
  2514.  
  2515.     for (;;) {
  2516.     /*
  2517.      * If we are using 1 bit/pixel, we don't need to allocate
  2518.      * any colors (we just use the foreground and background
  2519.      * colors in the GC).
  2520.      */
  2521.  
  2522.     if (mono && (nRed <= 2)) {
  2523.         colorPtr->flags |= BLACK_AND_WHITE;
  2524.         return;
  2525.     }
  2526.  
  2527.     /*
  2528.      * Calculate the RGB coordinates of the colors we want to
  2529.      * allocate and store them in *colors.
  2530.      */
  2531.  
  2532.     if ((colorPtr->visualInfo.class == DirectColor)
  2533.         || (colorPtr->visualInfo.class == TrueColor)) {
  2534.  
  2535.         /*
  2536.          * Direct/True Color: allocate shades of red, green, blue
  2537.          * independently.
  2538.          */
  2539.  
  2540.         if (mono) {
  2541.         numColors = nGreen = nBlue = nRed;
  2542.         } else {
  2543.         numColors = MAX(MAX(nRed, nGreen), nBlue);
  2544.         }
  2545.         colors = (XColor *) ckalloc(numColors * sizeof(XColor));
  2546.  
  2547.         for (i = 0; i < numColors; ++i) {
  2548.         if (igam == 1.0) {
  2549.             colors[i].red = CFRAC(i, nRed - 1);
  2550.             colors[i].green = CFRAC(i, nGreen - 1);
  2551.             colors[i].blue = CFRAC(i, nBlue - 1);
  2552.         } else {
  2553.             colors[i].red = CGFRAC(i, nRed - 1, igam);
  2554.             colors[i].green = CGFRAC(i, nGreen - 1, igam);
  2555.             colors[i].blue = CGFRAC(i, nBlue - 1, igam);
  2556.         }
  2557.         }
  2558.     } else {
  2559.         /*
  2560.          * PseudoColor, StaticColor, GrayScale or StaticGray visual:
  2561.          * we have to allocate each color in the color cube separately.
  2562.          */
  2563.  
  2564.         numColors = (mono) ? nRed: (nRed * nGreen * nBlue);
  2565.         colors = (XColor *) ckalloc(numColors * sizeof(XColor));
  2566.  
  2567.         if (!mono) {
  2568.         /*
  2569.          * Color display using a PseudoColor or StaticColor visual.
  2570.          */
  2571.  
  2572.         i = 0;
  2573.         for (r = 0; r < nRed; ++r) {
  2574.             for (g = 0; g < nGreen; ++g) {
  2575.             for (b = 0; b < nBlue; ++b) {
  2576.                 if (igam == 1.0) {
  2577.                 colors[i].red = CFRAC(r, nRed - 1);
  2578.                 colors[i].green = CFRAC(g, nGreen - 1);
  2579.                 colors[i].blue = CFRAC(b, nBlue - 1);
  2580.                 } else {
  2581.                 colors[i].red = CGFRAC(r, nRed - 1, igam);
  2582.                 colors[i].green = CGFRAC(g, nGreen - 1, igam);
  2583.                 colors[i].blue = CGFRAC(b, nBlue - 1, igam);
  2584.                 }
  2585.                 i++;
  2586.             }
  2587.             }
  2588.         }
  2589.         } else {
  2590.         /*
  2591.          * Monochrome display - allocate the shades of grey we want.
  2592.          */
  2593.  
  2594.         for (i = 0; i < numColors; ++i) {
  2595.             if (igam == 1.0) {
  2596.             r = CFRAC(i, numColors - 1);
  2597.             } else {
  2598.             r = CGFRAC(i, numColors - 1, igam);
  2599.             }
  2600.             colors[i].red = colors[i].green = colors[i].blue = r;
  2601.         }
  2602.         }
  2603.     }
  2604.  
  2605.     /*
  2606.      * Now try to allocate the colors we've calculated.
  2607.      */
  2608.  
  2609.     pixels = (unsigned long *) ckalloc(numColors * sizeof(unsigned long));
  2610.     for (i = 0; i < numColors; ++i) {
  2611.         if (!XAllocColor(colorPtr->id.display, colorPtr->id.colormap,
  2612.             &colors[i])) {
  2613.  
  2614.         /*
  2615.          * Can't get all the colors we want in the default colormap;
  2616.          * first try freeing colors from other unused color tables.
  2617.          */
  2618.  
  2619.         if (!ReclaimColors(&colorPtr->id, numColors - i)
  2620.             || !XAllocColor(colorPtr->id.display,
  2621.             colorPtr->id.colormap, &colors[i])) {
  2622.             /*
  2623.              * Still can't allocate the color.
  2624.              */
  2625.             break;
  2626.         }
  2627.         }
  2628.         pixels[i] = colors[i].pixel;
  2629.     }
  2630.  
  2631.     /*
  2632.      * If we didn't get all of the colors, reduce the
  2633.      * resolution of the color cube, free the ones we got,
  2634.      * and try again.
  2635.      */
  2636.  
  2637.     if (i >= numColors) {
  2638.         break;
  2639.     }
  2640.     XFreeColors(colorPtr->id.display, colorPtr->id.colormap, pixels, i, 0);
  2641.     ckfree((char *) colors);
  2642.     ckfree((char *) pixels);
  2643.  
  2644.     if (!mono) {
  2645.         if ((nRed == 2) && (nGreen == 2) && (nBlue == 2)) {
  2646.         /*
  2647.          * Fall back to 1-bit monochrome display.
  2648.          */
  2649.  
  2650.         mono = 1;
  2651.         } else {
  2652.         /*
  2653.          * Reduce the number of shades of each primary to about
  2654.          * 3/4 of the previous value.  This should reduce the
  2655.          * total number of colors required to about half the
  2656.          * previous value for PseudoColor displays.
  2657.          */
  2658.  
  2659.         nRed = (nRed * 3 + 2) / 4;
  2660.         nGreen = (nGreen * 3 + 2) / 4;
  2661.         nBlue = (nBlue * 3 + 2) / 4;
  2662.         }
  2663.     } else {
  2664.         /*
  2665.          * Reduce the number of shades of gray to about 1/2.
  2666.          */
  2667.  
  2668.         nRed = nRed / 2;
  2669.     }
  2670.     }
  2671.     
  2672.     /*
  2673.      * We have allocated all of the necessary colors:
  2674.      * fill in various fields of the ColorTable record.
  2675.      */
  2676.  
  2677.     if (!mono) {
  2678.     colorPtr->flags |= COLOR_WINDOW;
  2679.     if ((colorPtr->visualInfo.class != DirectColor)
  2680.         && (colorPtr->visualInfo.class != TrueColor)) {
  2681.         colorPtr->flags |= MAP_COLORS;
  2682.     }
  2683.     }
  2684.  
  2685.     colorPtr->numColors = numColors;
  2686.     colorPtr->pixelMap = pixels;
  2687.  
  2688.     /*
  2689.      * Set up quantization tables for dithering.
  2690.      */
  2691.     rMult = nGreen * nBlue;
  2692.     for (i = 0; i < 256; ++i) {
  2693.     r = (i * (nRed - 1) + 127) / 255;
  2694.     if (mono) {
  2695.         fr = (double) colors[r].red / 65535.0;
  2696.         if (colorPtr->id.gamma != 1.0 ) {
  2697.         fr = pow(fr, colorPtr->id.gamma);
  2698.         }
  2699.         colorPtr->colorQuant[0][i] = (int)(fr * 255.99);
  2700.         colorPtr->redValues[i] = colors[r].pixel;
  2701.     } else {
  2702.         g = (i * (nGreen - 1) + 127) / 255;
  2703.         b = (i * (nBlue - 1) + 127) / 255;
  2704.         if ((colorPtr->visualInfo.class == DirectColor)
  2705.             || (colorPtr->visualInfo.class == TrueColor)) {
  2706.         colorPtr->redValues[i] = colors[r].pixel
  2707.             & colorPtr->visualInfo.red_mask;
  2708.         colorPtr->greenValues[i] = colors[g].pixel
  2709.             & colorPtr->visualInfo.green_mask;
  2710.         colorPtr->blueValues[i] = colors[b].pixel
  2711.             & colorPtr->visualInfo.blue_mask;
  2712.         } else {
  2713.         r *= rMult;
  2714.         g *= nBlue;
  2715.         colorPtr->redValues[i] = r;
  2716.         colorPtr->greenValues[i] = g;
  2717.         colorPtr->blueValues[i] = b;
  2718.         }
  2719.         fr = (double) colors[r].red / 65535.0;
  2720.         fg = (double) colors[g].green / 65535.0;
  2721.         fb = (double) colors[b].blue / 65535.0;
  2722.         if (colorPtr->id.gamma != 1.0) {
  2723.         fr = pow(fr, colorPtr->id.gamma);
  2724.         fg = pow(fg, colorPtr->id.gamma);
  2725.         fb = pow(fb, colorPtr->id.gamma);
  2726.         }
  2727.         colorPtr->colorQuant[0][i] = (int)(fr * 255.99);
  2728.         colorPtr->colorQuant[1][i] = (int)(fg * 255.99);
  2729.         colorPtr->colorQuant[2][i] = (int)(fb * 255.99);
  2730.     }
  2731.     }
  2732.  
  2733.     ckfree((char *) colors);
  2734. }
  2735.  
  2736. /*
  2737.  *----------------------------------------------------------------------
  2738.  *
  2739.  * DisposeColorTable --
  2740.  *
  2741.  *
  2742.  * Results:
  2743.  *    None.
  2744.  *
  2745.  * Side effects:
  2746.  *    The colors in the argument color table are freed, as is the
  2747.  *    color table structure itself.  The color table is removed
  2748.  *    from the hash table which is used to locate color tables.
  2749.  *
  2750.  *----------------------------------------------------------------------
  2751.  */
  2752.  
  2753. static void
  2754. DisposeColorTable(clientData)
  2755.     ClientData clientData;    /* Pointer to the ColorTable whose
  2756.                  * colors are to be released. */
  2757. {
  2758.     ColorTable *colorPtr;
  2759.     Tcl_HashEntry *entry;
  2760.     Tk_ErrorHandler handler;
  2761.  
  2762.     colorPtr = (ColorTable *) clientData;
  2763.     if (colorPtr->pixelMap != NULL) {
  2764.     if (colorPtr->numColors > 0) {
  2765.         /*
  2766.          * At this stage, it is possible that the colormap no
  2767.          * longer exists, so ignore any errors that occur.
  2768.          */
  2769.  
  2770.         handler = Tk_CreateErrorHandler(colorPtr->id.display, -1, -1, -1,
  2771.             (Tk_ErrorProc *) NULL, (ClientData) NULL);
  2772.         XFreeColors(colorPtr->id.display, colorPtr->id.colormap,
  2773.             colorPtr->pixelMap, colorPtr->numColors, 0);
  2774.         Tk_DeleteErrorHandler(handler);
  2775.     }
  2776.     ckfree((char *) colorPtr->pixelMap);
  2777.     }
  2778.  
  2779.     entry = Tcl_FindHashEntry(&imgPhotoColorHash, (char *) &colorPtr->id);
  2780.     if (entry != NULL) {
  2781.     Tcl_DeleteHashEntry(entry);
  2782.     }
  2783.  
  2784.     ckfree((char *) colorPtr);
  2785. }
  2786.  
  2787. /*
  2788.  *----------------------------------------------------------------------
  2789.  *
  2790.  * ReclaimColors --
  2791.  *
  2792.  *    This procedure is called to try to free up colors in the
  2793.  *    colormap used by a color table.  It looks for other color
  2794.  *    tables with the same colormap and with a zero live reference
  2795.  *    count, and frees their colors.  It only does so if there is
  2796.  *    the possibility of freeing up at least `numColors' colors.
  2797.  *
  2798.  * Results:
  2799.  *    The return value is TRUE if any colors were freed, FALSE
  2800.  *    otherwise.
  2801.  *
  2802.  * Side effects:
  2803.  *    ColorTables which are not currently in use may lose their
  2804.  *    color allocations.
  2805.  *
  2806.  *---------------------------------------------------------------------- */
  2807.  
  2808. static int
  2809. ReclaimColors(id, numColors)
  2810.     ColorTableId *id;        /* Pointer to information identifying
  2811.                  * the color table which needs more colors. */
  2812.     int numColors;        /* Number of colors required. */
  2813. {
  2814.     Tcl_HashSearch srch;
  2815.     Tcl_HashEntry *entry;
  2816.     ColorTable *colorPtr;
  2817.     int nAvail;
  2818.  
  2819.     /*
  2820.      * First scan through the color hash table to get an
  2821.      * upper bound on how many colors we might be able to free.
  2822.      */
  2823.  
  2824.     nAvail = 0;
  2825.     entry = Tcl_FirstHashEntry(&imgPhotoColorHash, &srch);
  2826.     while (entry != NULL) {
  2827.     colorPtr = (ColorTable *) Tcl_GetHashValue(entry);
  2828.     if ((colorPtr->id.display == id->display)
  2829.         && (colorPtr->id.colormap == id->colormap)
  2830.         && (colorPtr->liveRefCount == 0 )&& (colorPtr->numColors != 0)
  2831.         && ((colorPtr->id.palette != id->palette)
  2832.         || (colorPtr->id.gamma != id->gamma))) {
  2833.  
  2834.         /*
  2835.          * We could take this guy's colors off him.
  2836.          */
  2837.  
  2838.         nAvail += colorPtr->numColors;
  2839.     }
  2840.     entry = Tcl_NextHashEntry(&srch);
  2841.     }
  2842.  
  2843.     /*
  2844.      * nAvail is an (over)estimate of the number of colors we could free.
  2845.      */
  2846.  
  2847.     if (nAvail < numColors) {
  2848.     return 0;
  2849.     }
  2850.  
  2851.     /*
  2852.      * Scan through a second time freeing colors.
  2853.      */
  2854.  
  2855.     entry = Tcl_FirstHashEntry(&imgPhotoColorHash, &srch);
  2856.     while ((entry != NULL) && (numColors > 0)) {
  2857.     colorPtr = (ColorTable *) Tcl_GetHashValue(entry);
  2858.     if ((colorPtr->id.display == id->display)
  2859.         && (colorPtr->id.colormap == id->colormap)
  2860.         && (colorPtr->liveRefCount == 0) && (colorPtr->numColors != 0)
  2861.         && ((colorPtr->id.palette != id->palette)
  2862.             || (colorPtr->id.gamma != id->gamma))) {
  2863.  
  2864.         /*
  2865.          * Free the colors that this ColorTable has.
  2866.          */
  2867.  
  2868.         XFreeColors(colorPtr->id.display, colorPtr->id.colormap,
  2869.             colorPtr->pixelMap, colorPtr->numColors, 0);
  2870.         numColors -= colorPtr->numColors;
  2871.         colorPtr->numColors = 0;
  2872.         ckfree((char *) colorPtr->pixelMap);
  2873.         colorPtr->pixelMap = NULL;
  2874.     }
  2875.  
  2876.     entry = Tcl_NextHashEntry(&srch);
  2877.     }
  2878.     return 1;            /* we freed some colors */
  2879. }
  2880.  
  2881. /*
  2882.  *----------------------------------------------------------------------
  2883.  *
  2884.  * DisposeInstance --
  2885.  *
  2886.  *    This procedure is called to finally free up an instance
  2887.  *    of a photo image which is no longer required.
  2888.  *
  2889.  * Results:
  2890.  *    None.
  2891.  *
  2892.  * Side effects:
  2893.  *    The instance data structure and the resources it references
  2894.  *    are freed.
  2895.  *
  2896.  *----------------------------------------------------------------------
  2897.  */
  2898.  
  2899. static void
  2900. DisposeInstance(clientData)
  2901.     ClientData clientData;    /* Pointer to the instance whose resources
  2902.                  * are to be released. */
  2903. {
  2904.     PhotoInstance *instancePtr = (PhotoInstance *) clientData;
  2905.     PhotoInstance *prevPtr;
  2906.  
  2907.     if (instancePtr->pixels != None) {
  2908.     Tk_FreePixmap(instancePtr->display, instancePtr->pixels);
  2909.     }
  2910.     if (instancePtr->gc != None) {
  2911.     Tk_FreeGC(instancePtr->display, instancePtr->gc);
  2912.     }
  2913.     if (instancePtr->imagePtr != NULL) {
  2914.     XFree((char *) instancePtr->imagePtr);
  2915.     }
  2916.     if (instancePtr->error != NULL) {
  2917.     ckfree((char *) instancePtr->error);
  2918.     }
  2919.     if (instancePtr->colorTablePtr != NULL) {
  2920.     FreeColorTable(instancePtr->colorTablePtr);
  2921.     }
  2922.  
  2923.     if (instancePtr->masterPtr->instancePtr == instancePtr) {
  2924.     instancePtr->masterPtr->instancePtr = instancePtr->nextPtr;
  2925.     } else {
  2926.     for (prevPtr = instancePtr->masterPtr->instancePtr;
  2927.         prevPtr->nextPtr != instancePtr; prevPtr = prevPtr->nextPtr) {
  2928.         /* Empty loop body */
  2929.     }
  2930.     prevPtr->nextPtr = instancePtr->nextPtr;
  2931.     }
  2932.     ckfree((char *) instancePtr);
  2933. }
  2934.  
  2935. /*
  2936.  *----------------------------------------------------------------------
  2937.  *
  2938.  * MatchFileFormat --
  2939.  *
  2940.  *    This procedure is called to find a photo image file format
  2941.  *    handler which can parse the image data in the given file.
  2942.  *    If a user-specified format string is provided, only handlers
  2943.  *    whose names match a prefix of the format string are tried.
  2944.  *
  2945.  * Results:
  2946.  *    A standard TCL return value.  If the return value is TCL_OK, a
  2947.  *    pointer to the image format record is returned in
  2948.  *    *imageFormatPtr, and the width and height of the image are
  2949.  *    returned in *widthPtr and *heightPtr.
  2950.  *
  2951.  * Side effects:
  2952.  *    None.
  2953.  *
  2954.  *----------------------------------------------------------------------
  2955.  */
  2956.  
  2957. static int
  2958. MatchFileFormat(interp, f, fileName, formatString, imageFormatPtr,
  2959.     widthPtr, heightPtr)
  2960.     Tcl_Interp *interp;        /* Interpreter to use for reporting errors. */
  2961.     FILE *f;            /* The image file, open for reading. */
  2962.     char *fileName;        /* The name of the image file. */
  2963.     char *formatString;        /* User-specified format string, or NULL. */
  2964.     Tk_PhotoImageFormat **imageFormatPtr;
  2965.                 /* A pointer to the photo image format
  2966.                  * record is returned here. */
  2967.     int *widthPtr, *heightPtr;    /* The dimensions of the image are
  2968.                  * returned here. */
  2969. {
  2970.     int matched;
  2971.     Tk_PhotoImageFormat *formatPtr;
  2972.  
  2973.     /*
  2974.      * Scan through the table of file format handlers to find
  2975.      * one which can handle the image.
  2976.      */
  2977.  
  2978.     matched = 0;
  2979.     for (formatPtr = formatList; formatPtr != NULL;
  2980.      formatPtr = formatPtr->nextPtr) {
  2981.     if ((formatString != NULL)
  2982.         && (strncasecmp(formatString, formatPtr->name,
  2983.         strlen(formatPtr->name)) != 0)) {
  2984.         continue;
  2985.     }
  2986.     matched = 1;
  2987.     if (formatPtr->fileMatchProc != NULL) {
  2988.         fseek(f, 0L, SEEK_SET);
  2989.         if ((*formatPtr->fileMatchProc)(f, fileName, formatString,
  2990.             widthPtr, heightPtr)) {
  2991.         if (*widthPtr < 1) {
  2992.             *widthPtr = 1;
  2993.         }
  2994.         if (*heightPtr < 1) {
  2995.             *heightPtr = 1;
  2996.         }
  2997.         break;
  2998.         }
  2999.     }
  3000.     }
  3001.  
  3002.     if (formatPtr == NULL) {
  3003.     if ((formatString != NULL) && !matched) {
  3004.         Tcl_AppendResult(interp, "image file format \"", formatString,
  3005.             "\" is unknown", (char *) NULL);
  3006.     } else {
  3007.         Tcl_AppendResult(interp,
  3008.             "couldn't recognize data in image file \"",
  3009.             fileName, "\"", (char *) NULL);
  3010.     }
  3011.     return TCL_ERROR;
  3012.     }
  3013.  
  3014.     *imageFormatPtr = formatPtr;
  3015.     fseek(f, 0L, SEEK_SET);
  3016.     return TCL_OK;
  3017. }
  3018.  
  3019. /*
  3020.  *----------------------------------------------------------------------
  3021.  *
  3022.  * MatchStringFormat --
  3023.  *
  3024.  *    This procedure is called to find a photo image file format
  3025.  *    handler which can parse the image data in the given string.
  3026.  *    If a user-specified format string is provided, only handlers
  3027.  *    whose names match a prefix of the format string are tried.
  3028.  *
  3029.  * Results:
  3030.  *    A standard TCL return value.  If the return value is TCL_OK, a
  3031.  *    pointer to the image format record is returned in
  3032.  *    *imageFormatPtr, and the width and height of the image are
  3033.  *    returned in *widthPtr and *heightPtr.
  3034.  *
  3035.  * Side effects:
  3036.  *    None.
  3037.  *
  3038.  *----------------------------------------------------------------------
  3039.  */
  3040.  
  3041. static int
  3042. MatchStringFormat(interp, string, formatString, imageFormatPtr,
  3043.     widthPtr, heightPtr)
  3044.     Tcl_Interp *interp;        /* Interpreter to use for reporting errors. */
  3045.     char *string;        /* String containing the image data. */
  3046.     char *formatString;        /* User-specified format string, or NULL. */
  3047.     Tk_PhotoImageFormat **imageFormatPtr;
  3048.                 /* A pointer to the photo image format
  3049.                  * record is returned here. */
  3050.     int *widthPtr, *heightPtr;    /* The dimensions of the image are
  3051.                  * returned here. */
  3052. {
  3053.     int matched;
  3054.     Tk_PhotoImageFormat *formatPtr;
  3055.  
  3056.     /*
  3057.      * Scan through the table of file format handlers to find
  3058.      * one which can handle the image.
  3059.      */
  3060.     matched = 0;
  3061.     for (formatPtr = formatList; formatPtr != NULL;
  3062.         formatPtr = formatPtr->nextPtr) {
  3063.     if ((formatString != NULL) && (strncasecmp(formatString,
  3064.         formatPtr->name, strlen(formatPtr->name)) != 0)) {
  3065.         continue;
  3066.     }
  3067.     matched = 1;
  3068.     if ((formatPtr->stringMatchProc != NULL)
  3069.         && (*formatPtr->stringMatchProc)(string, formatString,
  3070.         widthPtr, heightPtr)) {
  3071.         break;
  3072.     }
  3073.     }
  3074.  
  3075.     if (formatPtr == NULL) {
  3076.     if ((formatString != NULL) && !matched) {
  3077.         Tcl_AppendResult(interp, "image file format \"", formatString,
  3078.             "\" is unknown", (char *) NULL);
  3079.     } else {
  3080.         Tcl_AppendResult(interp, "no format found to parse",
  3081.             " image data string", (char *) NULL);
  3082.     }
  3083.     return TCL_ERROR;
  3084.     }
  3085.  
  3086.     *imageFormatPtr = formatPtr;
  3087.     return TCL_OK;
  3088. }
  3089.  
  3090. /*
  3091.  *----------------------------------------------------------------------
  3092.  *
  3093.  * Tk_FindPhoto --
  3094.  *
  3095.  *    This procedure is called to get an opaque handle (actually a
  3096.  *    PhotoMaster *) for a given image, which can be used in
  3097.  *    subsequent calls to Tk_PhotoPutBlock, etc.  The `name'
  3098.  *    parameter is the name of the image.
  3099.  *
  3100.  * Results:
  3101.  *    The handle for the photo image, or NULL if there is no
  3102.  *    photo image with the name given.
  3103.  *
  3104.  * Side effects:
  3105.  *    None.
  3106.  *
  3107.  *----------------------------------------------------------------------
  3108.  */
  3109.  
  3110. Tk_PhotoHandle
  3111. Tk_FindPhoto(imageName)
  3112.     char *imageName;        /* Name of the desired photo image. */
  3113. {
  3114.     Tcl_HashEntry *entry;
  3115.  
  3116.     if (!imgPhotoHashInitialized) {
  3117.     return NULL;
  3118.     }
  3119.     entry = Tcl_FindHashEntry(&imgPhotoHash, imageName);
  3120.     if (entry == NULL) {
  3121.     return NULL;
  3122.     }
  3123.     return (Tk_PhotoHandle) Tcl_GetHashValue(entry);
  3124. }
  3125.  
  3126. /*
  3127.  *----------------------------------------------------------------------
  3128.  *
  3129.  * Tk_PhotoPutBlock --
  3130.  *
  3131.  *    This procedure is called to put image data into a photo image.
  3132.  *
  3133.  * Results:
  3134.  *    None.
  3135.  *
  3136.  * Side effects:
  3137.  *    The image data is stored.  The image may be expanded.
  3138.  *    The Tk image code is informed that the image has changed.
  3139.  *
  3140.  *---------------------------------------------------------------------- */
  3141.  
  3142. void
  3143. Tk_PhotoPutBlock(handle, blockPtr, x, y, width, height)
  3144.     Tk_PhotoHandle handle;    /* Opaque handle for the photo image
  3145.                  * to be updated. */
  3146.     register Tk_PhotoImageBlock *blockPtr;
  3147.                 /* Pointer to a structure describing the
  3148.                  * pixel data to be copied into the image. */
  3149.     int x, y;            /* Coordinates of the top-left pixel to
  3150.                  * be updated in the image. */
  3151.     int width, height;        /* Dimensions of the area of the image
  3152.                  * to be updated. */
  3153. {
  3154.     register PhotoMaster *masterPtr;
  3155.     int xEnd, yEnd;
  3156.     int greenOffset, blueOffset;
  3157.     int wLeft, hLeft;
  3158.     int wCopy, hCopy;
  3159.     unsigned char *srcPtr, *srcLinePtr;
  3160.     unsigned char *destPtr, *destLinePtr;
  3161.     int pitch;
  3162.     XRectangle rect;
  3163.  
  3164.     masterPtr = (PhotoMaster *) handle;
  3165.  
  3166.     if ((masterPtr->userWidth != 0) && ((x + width) > masterPtr->userWidth)) {
  3167.     width = masterPtr->userWidth - x;
  3168.     }
  3169.     if ((masterPtr->userHeight != 0)
  3170.         && ((y + height) > masterPtr->userHeight)) {
  3171.     height = masterPtr->userHeight - y;
  3172.     }
  3173.     if ((width <= 0) || (height <= 0))
  3174.     return;
  3175.  
  3176.     xEnd = x + width;
  3177.     yEnd = y + height;
  3178.     if ((xEnd > masterPtr->width) || (yEnd > masterPtr->height)) {
  3179.     ImgPhotoSetSize(masterPtr, xEnd, yEnd);
  3180.     }
  3181.  
  3182.     if ((y < masterPtr->ditherY) || ((y == masterPtr->ditherY)
  3183.         && (x < masterPtr->ditherX))) {
  3184.     /*
  3185.      * The dithering isn't correct past the start of this block.
  3186.      */
  3187.     masterPtr->ditherX = x;
  3188.     masterPtr->ditherY = y;
  3189.     }
  3190.  
  3191.     /*
  3192.      * If this image block could have different red, green and blue
  3193.      * components, mark it as a color image.
  3194.      */
  3195.  
  3196.     greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
  3197.     blueOffset = blockPtr->offset[2] - blockPtr->offset[0];
  3198.     if ((greenOffset != 0) || (blueOffset != 0)) {
  3199.     masterPtr->flags |= COLOR_IMAGE;
  3200.     }
  3201.  
  3202.     /*
  3203.      * Copy the data into our local 24-bit/pixel array.
  3204.      * If we can do it with a single memcpy, we do.
  3205.      */
  3206.  
  3207.     destLinePtr = masterPtr->pix24 + (y * masterPtr->width + x) * 3;
  3208.     pitch = masterPtr->width * 3;
  3209.  
  3210.     if ((blockPtr->pixelSize == 3) && (greenOffset == 1) && (blueOffset == 2)
  3211.         && (width <= blockPtr->width) && (height <= blockPtr->height)
  3212.         && ((height == 1) || ((x == 0) && (width == masterPtr->width)
  3213.         && (blockPtr->pitch == pitch)))) {
  3214.     memcpy((VOID *) destLinePtr,
  3215.         (VOID *) (blockPtr->pixelPtr + blockPtr->offset[0]),
  3216.         (size_t) (height * pitch));
  3217.     } else {
  3218.     for (hLeft = height; hLeft > 0;) {
  3219.         srcLinePtr = blockPtr->pixelPtr + blockPtr->offset[0];
  3220.         hCopy = MIN(hLeft, blockPtr->height);
  3221.         hLeft -= hCopy;
  3222.         for (; hCopy > 0; --hCopy) {
  3223.         destPtr = destLinePtr;
  3224.         for (wLeft = width; wLeft > 0;) {
  3225.             wCopy = MIN(wLeft, blockPtr->width);
  3226.             wLeft -= wCopy;
  3227.             srcPtr = srcLinePtr;
  3228.             for (; wCopy > 0; --wCopy) {
  3229.             *destPtr++ = srcPtr[0];
  3230.             *destPtr++ = srcPtr[greenOffset];
  3231.             *destPtr++ = srcPtr[blueOffset];
  3232.             srcPtr += blockPtr->pixelSize;
  3233.             }
  3234.         }
  3235.         srcLinePtr += blockPtr->pitch;
  3236.         destLinePtr += pitch;
  3237.         }
  3238.     }
  3239.     }
  3240.  
  3241.     /*
  3242.      * Add this new block to the region which specifies which data is valid.
  3243.      */
  3244.  
  3245.     rect.x = x;
  3246.     rect.y = y;
  3247.     rect.width = width;
  3248.     rect.height = height;
  3249.     XUnionRectWithRegion(&rect, masterPtr->validRegion,
  3250.         masterPtr->validRegion);
  3251.  
  3252.     /*
  3253.      * Update each instance.
  3254.      */
  3255.  
  3256.     Dither(masterPtr, x, y, width, height);
  3257.  
  3258.     /*
  3259.      * Tell the core image code that this image has changed.
  3260.      */
  3261.  
  3262.     Tk_ImageChanged(masterPtr->tkMaster, x, y, width, height, masterPtr->width,
  3263.         masterPtr->height);
  3264. }
  3265.  
  3266. /*
  3267.  *----------------------------------------------------------------------
  3268.  *
  3269.  * Tk_PhotoPutZoomedBlock --
  3270.  *
  3271.  *    This procedure is called to put image data into a photo image,
  3272.  *    with possible subsampling and/or zooming of the pixels.
  3273.  *
  3274.  * Results:
  3275.  *    None.
  3276.  *
  3277.  * Side effects:
  3278.  *    The image data is stored.  The image may be expanded.
  3279.  *    The Tk image code is informed that the image has changed.
  3280.  *
  3281.  *----------------------------------------------------------------------
  3282.  */
  3283.  
  3284. void
  3285. Tk_PhotoPutZoomedBlock(handle, blockPtr, x, y, width, height, zoomX, zoomY,
  3286.     subsampleX, subsampleY)
  3287.     Tk_PhotoHandle handle;    /* Opaque handle for the photo image
  3288.                  * to be updated. */
  3289.     register Tk_PhotoImageBlock *blockPtr;
  3290.                 /* Pointer to a structure describing the
  3291.                  * pixel data to be copied into the image. */
  3292.     int x, y;            /* Coordinates of the top-left pixel to
  3293.                  * be updated in the image. */
  3294.     int width, height;        /* Dimensions of the area of the image
  3295.                  * to be updated. */
  3296.     int zoomX, zoomY;        /* Zoom factors for the X and Y axes. */
  3297.     int subsampleX, subsampleY;    /* Subsampling factors for the X and Y axes. */
  3298. {
  3299.     register PhotoMaster *masterPtr;
  3300.     int xEnd, yEnd;
  3301.     int greenOffset, blueOffset;
  3302.     int wLeft, hLeft;
  3303.     int wCopy, hCopy;
  3304.     int blockWid, blockHt;
  3305.     unsigned char *srcPtr, *srcLinePtr, *srcOrigPtr;
  3306.     unsigned char *destPtr, *destLinePtr;
  3307.     int pitch;
  3308.     int xRepeat, yRepeat;
  3309.     int blockXSkip, blockYSkip;
  3310.     XRectangle rect;
  3311.  
  3312.     if ((zoomX == 1) && (zoomY == 1) && (subsampleX == 1)
  3313.         && (subsampleY == 1)) {
  3314.     Tk_PhotoPutBlock(handle, blockPtr, x, y, width, height);
  3315.     return;
  3316.     }
  3317.  
  3318.     masterPtr = (PhotoMaster *) handle;
  3319.  
  3320.     if ((zoomX <= 0) || (zoomY <= 0))
  3321.     return;
  3322.     if ((masterPtr->userWidth != 0) && ((x + width) > masterPtr->userWidth)) {
  3323.     width = masterPtr->userWidth - x;
  3324.     }
  3325.     if ((masterPtr->userHeight != 0)
  3326.         && ((y + height) > masterPtr->userHeight)) {
  3327.     height = masterPtr->userHeight - y;
  3328.     }
  3329.     if ((width <= 0) || (height <= 0))
  3330.     return;
  3331.  
  3332.     xEnd = x + width;
  3333.     yEnd = y + height;
  3334.     if ((xEnd > masterPtr->width) || (yEnd > masterPtr->height)) {
  3335.     ImgPhotoSetSize(masterPtr, xEnd, yEnd);
  3336.     }
  3337.  
  3338.     if ((y < masterPtr->ditherY) || ((y == masterPtr->ditherY)
  3339.        && (x < masterPtr->ditherX))) {
  3340.     /*
  3341.      * The dithering isn't correct past the start of this block.
  3342.      */
  3343.  
  3344.     masterPtr->ditherX = x;
  3345.     masterPtr->ditherY = y;
  3346.     }
  3347.  
  3348.     /*
  3349.      * If this image block could have different red, green and blue
  3350.      * components, mark it as a color image.
  3351.      */
  3352.  
  3353.     greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
  3354.     blueOffset = blockPtr->offset[2] - blockPtr->offset[0];
  3355.     if ((greenOffset != 0) || (blueOffset != 0)) {
  3356.     masterPtr->flags |= COLOR_IMAGE;
  3357.     }
  3358.  
  3359.     /*
  3360.      * Work out what area the pixel data in the block expands to after
  3361.      * subsampling and zooming.
  3362.      */
  3363.  
  3364.     blockXSkip = subsampleX * blockPtr->pixelSize;
  3365.     blockYSkip = subsampleY * blockPtr->pitch;
  3366.     if (subsampleX > 0)
  3367.     blockWid = ((blockPtr->width + subsampleX - 1) / subsampleX) * zoomX;
  3368.     else if (subsampleX == 0)
  3369.     blockWid = width;
  3370.     else
  3371.     blockWid = ((blockPtr->width - subsampleX - 1) / -subsampleX) * zoomX;
  3372.     if (subsampleY > 0)
  3373.     blockHt = ((blockPtr->height + subsampleY - 1) / subsampleY) * zoomY;
  3374.     else if (subsampleY == 0)
  3375.     blockHt = height;
  3376.     else
  3377.     blockHt = ((blockPtr->height - subsampleY - 1) / -subsampleY) * zoomY;
  3378.  
  3379.     /*
  3380.      * Copy the data into our local 24-bit/pixel array.
  3381.      */
  3382.  
  3383.     destLinePtr = masterPtr->pix24 + (y * masterPtr->width + x) * 3;
  3384.     srcOrigPtr = blockPtr->pixelPtr + blockPtr->offset[0];
  3385.     if (subsampleX < 0) {
  3386.     srcOrigPtr += (blockPtr->width - 1) * blockPtr->pixelSize;
  3387.     }
  3388.     if (subsampleY < 0) {
  3389.     srcOrigPtr += (blockPtr->height - 1) * blockPtr->pitch;
  3390.     }
  3391.  
  3392.     pitch = masterPtr->width * 3;
  3393.     for (hLeft = height; hLeft > 0; ) {
  3394.     hCopy = MIN(hLeft, blockHt);
  3395.     hLeft -= hCopy;
  3396.     yRepeat = zoomY;
  3397.     srcLinePtr = srcOrigPtr;
  3398.     for (; hCopy > 0; --hCopy) {
  3399.         destPtr = destLinePtr;
  3400.         for (wLeft = width; wLeft > 0;) {
  3401.         wCopy = MIN(wLeft, blockWid);
  3402.         wLeft -= wCopy;
  3403.         srcPtr = srcLinePtr;
  3404.         for (; wCopy > 0; wCopy -= zoomX) {
  3405.             for (xRepeat = MIN(wCopy, zoomX); xRepeat > 0; xRepeat--) {
  3406.             *destPtr++ = srcPtr[0];
  3407.             *destPtr++ = srcPtr[greenOffset];
  3408.             *destPtr++ = srcPtr[blueOffset];
  3409.             }
  3410.             srcPtr += blockXSkip;
  3411.         }
  3412.         }
  3413.         destLinePtr += pitch;
  3414.         yRepeat--;
  3415.         if (yRepeat <= 0) {
  3416.         srcLinePtr += blockYSkip;
  3417.         yRepeat = zoomY;
  3418.         }
  3419.     }
  3420.     }
  3421.  
  3422.     /*
  3423.      * Add this new block to the region that specifies which data is valid.
  3424.      */
  3425.  
  3426.     rect.x = x;
  3427.     rect.y = y;
  3428.     rect.width = width;
  3429.     rect.height = height;
  3430.     XUnionRectWithRegion(&rect, masterPtr->validRegion,
  3431.         masterPtr->validRegion);
  3432.  
  3433.     /*
  3434.      * Update each instance.
  3435.      */
  3436.  
  3437.     Dither(masterPtr, x, y, width, height);
  3438.  
  3439.     /*
  3440.      * Tell the core image code that this image has changed.
  3441.      */
  3442.  
  3443.     Tk_ImageChanged(masterPtr->tkMaster, x, y, width, height, masterPtr->width,
  3444.         masterPtr->height);
  3445. }
  3446.  
  3447. /*
  3448.  *----------------------------------------------------------------------
  3449.  *
  3450.  * Dither --
  3451.  *
  3452.  *    This procedure is called to update an area of each instance's
  3453.  *    pixmap by dithering the corresponding area of the image master.
  3454.  *
  3455.  * Results:
  3456.  *    None.
  3457.  *
  3458.  * Side effects:
  3459.  *    The pixmap of each instance of this image gets updated.
  3460.  *    The fields in *masterPtr indicating which area of the image
  3461.  *    is correctly dithered get updated.
  3462.  *
  3463.  *----------------------------------------------------------------------
  3464.  */
  3465.  
  3466. static void
  3467. Dither(masterPtr, x, y, width, height)
  3468.     PhotoMaster *masterPtr;    /* Image master whose instances are
  3469.                  * to be updated. */
  3470.     int x, y;            /* Coordinates of the top-left pixel
  3471.                  * in the area to be dithered. */
  3472.     int width, height;        /* Dimensions of the area to be dithered. */
  3473. {
  3474.     PhotoInstance *instancePtr;
  3475.  
  3476.     if ((width <= 0) || (height <= 0)) {
  3477.     return;
  3478.     }
  3479.  
  3480.     for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
  3481.         instancePtr = instancePtr->nextPtr) {
  3482.     DitherInstance(instancePtr, x, y, width, height);
  3483.     }
  3484.  
  3485.     /*
  3486.      * Work out whether this block will be correctly dithered
  3487.      * and whether it will extend the correctly dithered region.
  3488.      */
  3489.  
  3490.     if (((y < masterPtr->ditherY)
  3491.         || ((y == masterPtr->ditherY) && (x <= masterPtr->ditherX)))
  3492.         && ((y + height) > (masterPtr->ditherY))) {
  3493.  
  3494.     /*
  3495.      * This block starts inside (or immediately after) the correctly
  3496.      * dithered region, so the first scan line at least will be right.
  3497.      * Furthermore this block extends into scanline masterPtr->ditherY.
  3498.      */
  3499.  
  3500.     if ((x == 0) && (width == masterPtr->width)) {
  3501.         /*
  3502.          * We are doing the full width, therefore the dithering
  3503.          * will be correct to the end.
  3504.          */
  3505.  
  3506.         masterPtr->ditherX = 0;
  3507.         masterPtr->ditherY = y + height;
  3508.     } else {
  3509.         /*
  3510.          * We are doing partial scanlines, therefore the
  3511.          * correctly-dithered region will be extended by
  3512.          * at most one scan line.
  3513.          */
  3514.  
  3515.         if (x <= masterPtr->ditherX) {
  3516.         masterPtr->ditherX = x + width;
  3517.         if (masterPtr->ditherX >= masterPtr->width) {
  3518.             masterPtr->ditherX = 0;
  3519.             masterPtr->ditherY++;
  3520.         }
  3521.         }
  3522.     }
  3523.     }
  3524.  
  3525. }    
  3526.  
  3527. /*
  3528.  *----------------------------------------------------------------------
  3529.  *
  3530.  * DitherInstance --
  3531.  *
  3532.  *    This procedure is called to update an area of an instance's
  3533.  *    pixmap by dithering the corresponding area of the master.
  3534.  *
  3535.  * Results:
  3536.  *    None.
  3537.  *
  3538.  * Side effects:
  3539.  *    The instance's pixmap gets updated.
  3540.  *
  3541.  *----------------------------------------------------------------------
  3542.  */
  3543.  
  3544. static void
  3545. DitherInstance(instancePtr, xStart, yStart, width, height)
  3546.     PhotoInstance *instancePtr;    /* The instance to be updated. */
  3547.     int xStart, yStart;        /* Coordinates of the top-left pixel in the
  3548.                  * block to be dithered. */
  3549.     int width, height;        /* Dimensions of the block to be dithered. */
  3550. {
  3551.     PhotoMaster *masterPtr;
  3552.     ColorTable *colorPtr;
  3553.     XImage *imagePtr;
  3554.     int nLines, bigEndian;
  3555.     int i, c, x, y;
  3556.     int xEnd, yEnd;
  3557.     int bitsPerPixel, bytesPerLine, lineLength;
  3558.     unsigned char *srcLinePtr, *srcPtr;
  3559.     schar *errLinePtr, *errPtr;
  3560.     unsigned char *destBytePtr, *dstLinePtr;
  3561.     pixel *destLongPtr;
  3562.     pixel firstBit, word, mask;
  3563.     int col[3];
  3564.     int doDithering = 1;
  3565.  
  3566.     colorPtr = instancePtr->colorTablePtr;
  3567.     masterPtr = instancePtr->masterPtr;
  3568.  
  3569.     /*
  3570.      * Turn dithering off in certain cases where it is not
  3571.      * needed (TrueColor, DirectColor with many colors).
  3572.      */
  3573.  
  3574.     if ((colorPtr->visualInfo.class == DirectColor)
  3575.         || (colorPtr->visualInfo.class == TrueColor)) {
  3576.     int nRed, nGreen, nBlue, result;
  3577.  
  3578.     result = sscanf(colorPtr->id.palette, "%d/%d/%d", &nRed,
  3579.         &nGreen, &nBlue);
  3580.     if ((nRed >= 256)
  3581.         && ((result == 1) || ((nGreen >= 256) && (nBlue >= 256)))) {
  3582.         doDithering = 0;
  3583.     }
  3584.     }
  3585.  
  3586.     /*
  3587.      * First work out how many lines to do at a time,
  3588.      * then how many bytes we'll need for pixel storage,
  3589.      * and allocate it.
  3590.      */
  3591.  
  3592.     nLines = (MAX_PIXELS + width - 1) / width;
  3593.     if (nLines < 1) {
  3594.     nLines = 1;
  3595.     }
  3596.     if (nLines > height ) {
  3597.     nLines = height;
  3598.     }
  3599.  
  3600.     imagePtr = instancePtr->imagePtr;
  3601.     if (imagePtr == NULL) {
  3602.     return;            /* we must be really tight on memory */
  3603.     }
  3604.     bitsPerPixel = imagePtr->bits_per_pixel;
  3605.     bytesPerLine = ((bitsPerPixel * width + 31) >> 3) & ~3;
  3606.     imagePtr->width = width;
  3607.     imagePtr->height = nLines;
  3608.     imagePtr->bytes_per_line = bytesPerLine;
  3609.     imagePtr->data = (char *) ckalloc((unsigned) (imagePtr->bytes_per_line * nLines));
  3610.     bigEndian = imagePtr->bitmap_bit_order == MSBFirst;
  3611.     firstBit = bigEndian? (1 << (imagePtr->bitmap_unit - 1)): 1;
  3612.  
  3613.     lineLength = masterPtr->width * 3;
  3614.     srcLinePtr = masterPtr->pix24 + yStart * lineLength + xStart * 3;
  3615.     errLinePtr = instancePtr->error + yStart * lineLength + xStart * 3;
  3616.     xEnd = xStart + width;
  3617.  
  3618.     /*
  3619.      * Loop over the image, doing at most nLines lines before
  3620.      * updating the screen image.
  3621.      */
  3622.  
  3623.     for (; height > 0; height -= nLines) {
  3624.     if (nLines > height) {
  3625.         nLines = height;
  3626.     }
  3627.     dstLinePtr = (unsigned char *) imagePtr->data;
  3628.     yEnd = yStart + nLines;
  3629.     for (y = yStart; y < yEnd; ++y) {
  3630.         srcPtr = srcLinePtr;
  3631.         errPtr = errLinePtr;
  3632.         destBytePtr = dstLinePtr;
  3633.         destLongPtr = (pixel *) dstLinePtr;
  3634.         if (colorPtr->flags & COLOR_WINDOW) {
  3635.         /*
  3636.          * Color window.  We dither the three components
  3637.          * independently, using Floyd-Steinberg dithering,
  3638.          * which propagates errors from the quantization of
  3639.          * pixels to the pixels below and to the right.
  3640.          */
  3641.  
  3642.         for (x = xStart; x < xEnd; ++x) {
  3643.             if (doDithering) {
  3644.             for (i = 0; i < 3; ++i) {
  3645.                 /*
  3646.                  * Compute the error propagated into this pixel
  3647.                  * for this component.
  3648.                  * If e[x,y] is the array of quantization error
  3649.                  * values, we compute
  3650.                  *     7/16 * e[x-1,y] + 1/16 * e[x-1,y-1]
  3651.                  *   + 5/16 * e[x,y-1] + 3/16 * e[x+1,y-1]
  3652.                  * and round it to an integer.
  3653.                  *
  3654.                  * The expression ((c + 2056) >> 4) - 128
  3655.                  * computes round(c / 16), and works correctly on
  3656.                  * machines without a sign-extending right shift.
  3657.                  */
  3658.                 
  3659.                 c = (x > 0) ? errPtr[-3] * 7: 0;
  3660.                 if (y > 0) {
  3661.                 if (x > 0) {
  3662.                     c += errPtr[-lineLength-3];
  3663.                 }
  3664.                 c += errPtr[-lineLength] * 5;
  3665.                 if ((x + 1) < masterPtr->width) {
  3666.                     c += errPtr[-lineLength+3] * 3;
  3667.                 }
  3668.                 }
  3669.                 
  3670.                 /*
  3671.                  * Add the propagated error to the value of this
  3672.                  * component, quantize it, and store the
  3673.                  * quantization error.
  3674.                  */
  3675.                 
  3676.                 c = ((c + 2056) >> 4) - 128 + *srcPtr++;
  3677.                 if (c < 0) {
  3678.                 c = 0;
  3679.                 } else if (c > 255) {
  3680.                 c = 255;
  3681.                 }
  3682.                 col[i] = colorPtr->colorQuant[i][c];
  3683.                 *errPtr++ = c - col[i];
  3684.             }
  3685.             } else {
  3686.             /* 
  3687.              * Output is virtually continuous in this case,
  3688.              * so don't bother dithering.
  3689.              */
  3690.  
  3691.             col[0] = *srcPtr++;
  3692.             col[1] = *srcPtr++;
  3693.             col[2] = *srcPtr++;
  3694.             }
  3695.  
  3696.             /*
  3697.              * Translate the quantized component values into
  3698.              * an X pixel value, and store it in the image.
  3699.              */
  3700.  
  3701.             i = colorPtr->redValues[col[0]]
  3702.                 + colorPtr->greenValues[col[1]]
  3703.                 + colorPtr->blueValues[col[2]];
  3704.             if (colorPtr->flags & MAP_COLORS) {
  3705.             i = colorPtr->pixelMap[i];
  3706.             }
  3707.             switch (bitsPerPixel) {
  3708.             case NBBY:
  3709.                 *destBytePtr++ = i;
  3710.                 break;
  3711.             case NBBY * sizeof(pixel):
  3712.                 *destLongPtr++ = i;
  3713.                 break;
  3714.             default:
  3715.                 XPutPixel(imagePtr, x - xStart, y - yStart,
  3716.                     (unsigned) i);
  3717.             }
  3718.         }
  3719.  
  3720.         } else if (bitsPerPixel > 1) {
  3721.         /*
  3722.          * Multibit monochrome window.  The operation here is similar
  3723.          * to the color window case above, except that there is only
  3724.          * one component.  If the master image is in color, use the
  3725.          * luminance computed as
  3726.          *    0.344 * red + 0.5 * green + 0.156 * blue.
  3727.          */
  3728.  
  3729.         for (x = xStart; x < xEnd; ++x) {
  3730.             c = (x > 0) ? errPtr[-1] * 7: 0;
  3731.             if (y > 0) {
  3732.             if (x > 0)  {
  3733.                 c += errPtr[-lineLength-1];
  3734.             }
  3735.             c += errPtr[-lineLength] * 5;
  3736.             if (x + 1 < masterPtr->width) {
  3737.                 c += errPtr[-lineLength+1] * 3;
  3738.             }
  3739.             }
  3740.             c = ((c + 2056) >> 4) - 128;
  3741.  
  3742.             if ((masterPtr->flags & COLOR_IMAGE) == 0) {
  3743.             c += srcPtr[0];
  3744.             } else {
  3745.             c += (unsigned)(srcPtr[0] * 11 + srcPtr[1] * 16
  3746.                     + srcPtr[2] * 5 + 16) >> 5;
  3747.             }
  3748.             srcPtr += 3;
  3749.  
  3750.             if (c < 0) {
  3751.             c = 0;
  3752.             } else if (c > 255) {
  3753.             c = 255;
  3754.             }
  3755.             i = colorPtr->colorQuant[0][c];
  3756.             *errPtr++ = c - i;
  3757.             i = colorPtr->redValues[i];
  3758.             switch (bitsPerPixel) {
  3759.             case NBBY:
  3760.                 *destBytePtr++ = i;
  3761.                 break;
  3762.             case NBBY * sizeof(pixel):
  3763.                 *destLongPtr++ = i;
  3764.                 break;
  3765.             default:
  3766.                 XPutPixel(imagePtr, x - xStart, y - yStart,
  3767.                     (unsigned) i);
  3768.             }
  3769.         }
  3770.         } else {
  3771.         /*
  3772.          * 1-bit monochrome window.  This is similar to the
  3773.          * multibit monochrome case above, except that the
  3774.          * quantization is simpler (we only have black = 0
  3775.          * and white = 255), and we produce an XY-Bitmap.
  3776.          */
  3777.  
  3778.         word = 0;
  3779.         mask = firstBit;
  3780.         for (x = xStart; x < xEnd; ++x) {
  3781.             /*
  3782.              * If we have accumulated a whole word, store it
  3783.              * in the image and start a new word.
  3784.              */
  3785.  
  3786.             if (mask == 0) {
  3787.             *destLongPtr++ = word;
  3788.             mask = firstBit;
  3789.             word = 0;
  3790.             }
  3791.  
  3792.             c = (x > 0) ? errPtr[-1] * 7: 0;
  3793.             if (y > 0) {
  3794.             if (x > 0) {
  3795.                 c += errPtr[-lineLength-1];
  3796.             }
  3797.             c += errPtr[-lineLength] * 5;
  3798.             if (x + 1 < masterPtr->width) {
  3799.                 c += errPtr[-lineLength+1] * 3;
  3800.             }
  3801.             }
  3802.             c = ((c + 2056) >> 4) - 128;
  3803.  
  3804.             if ((masterPtr->flags & COLOR_IMAGE) == 0) {
  3805.             c += srcPtr[0];
  3806.             } else {
  3807.             c += (unsigned)(srcPtr[0] * 11 + srcPtr[1] * 16
  3808.                     + srcPtr[2] * 5 + 16) >> 5;
  3809.             }
  3810.             srcPtr += 3;
  3811.  
  3812.             if (c < 0) {
  3813.             c = 0;
  3814.             } else if (c > 255) {
  3815.             c = 255;
  3816.             }
  3817.             if (c >= 128) {
  3818.             word |= mask;
  3819.             *errPtr++ = c - 255;
  3820.             } else {
  3821.             *errPtr++ = c;
  3822.             }
  3823.             mask = bigEndian? (mask >> 1): (mask << 1);
  3824.         }
  3825.         *destLongPtr = word;
  3826.         }
  3827.         srcLinePtr += lineLength;
  3828.         errLinePtr += lineLength;
  3829.         dstLinePtr += bytesPerLine;
  3830.     }
  3831.  
  3832.     /*
  3833.      * Update the pixmap for this instance with the block of
  3834.      * pixels that we have just computed.
  3835.      */
  3836.  
  3837.     XPutImage(instancePtr->display, instancePtr->pixels,
  3838.         instancePtr->gc, imagePtr, 0, 0, xStart, yStart,
  3839.         (unsigned) width, (unsigned) nLines);
  3840.     yStart = yEnd;
  3841.     
  3842.     }
  3843.  
  3844.     ckfree(imagePtr->data);
  3845.     imagePtr->data = NULL;
  3846. }
  3847.  
  3848. /*
  3849.  *----------------------------------------------------------------------
  3850.  *
  3851.  * Tk_PhotoBlank --
  3852.  *
  3853.  *    This procedure is called to clear an entire photo image.
  3854.  *
  3855.  * Results:
  3856.  *    None.
  3857.  *
  3858.  * Side effects:
  3859.  *    The valid region for the image is set to the null region.
  3860.  *    The generic image code is notified that the image has changed.
  3861.  *
  3862.  *----------------------------------------------------------------------
  3863.  */
  3864.  
  3865. void
  3866. Tk_PhotoBlank(handle)
  3867.     Tk_PhotoHandle handle;    /* Handle for the image to be blanked. */
  3868. {
  3869.     PhotoMaster *masterPtr;
  3870.     PhotoInstance *instancePtr;
  3871.  
  3872.     masterPtr = (PhotoMaster *) handle;
  3873.     masterPtr->ditherX = masterPtr->ditherY = 0;
  3874.     masterPtr->flags = 0;
  3875.  
  3876.     /*
  3877.      * The image has valid data nowhere.
  3878.      */
  3879.  
  3880.     if (masterPtr->validRegion != NULL) {
  3881.     XDestroyRegion(masterPtr->validRegion);
  3882.     }
  3883.     masterPtr->validRegion = XCreateRegion();
  3884.  
  3885.     /*
  3886.      * Clear out the 24-bit pixel storage array.
  3887.      * Clear out the dithering error arrays for each instance.
  3888.      */
  3889.  
  3890.     memset((VOID *) masterPtr->pix24, 0,
  3891.         (size_t) (masterPtr->width * masterPtr->height));
  3892.     for (instancePtr = masterPtr->instancePtr; instancePtr != NULL;
  3893.         instancePtr = instancePtr->nextPtr) {
  3894.     memset((VOID *) instancePtr->error, 0,
  3895.         (size_t) (masterPtr->width * masterPtr->height
  3896.             * sizeof(schar)));
  3897.     }
  3898.  
  3899.     /*
  3900.      * Tell the core image code that this image has changed.
  3901.      */
  3902.  
  3903.     Tk_ImageChanged(masterPtr->tkMaster, 0, 0, masterPtr->width,
  3904.         masterPtr->height, masterPtr->width, masterPtr->height);
  3905. }
  3906.  
  3907. /*
  3908.  *----------------------------------------------------------------------
  3909.  *
  3910.  * Tk_PhotoExpand --
  3911.  *
  3912.  *    This procedure is called to request that a photo image be
  3913.  *    expanded if necessary to be at least `width' pixels wide and
  3914.  *    `height' pixels high.  If the user has declared a definite
  3915.  *    image size (using the -width and -height configuration
  3916.  *    options) then this call has no effect.
  3917.  *
  3918.  * Results:
  3919.  *    None.
  3920.  *
  3921.  * Side effects:
  3922.  *    The size of the photo image may change; if so the generic
  3923.  *    image code is informed.
  3924.  *
  3925.  *----------------------------------------------------------------------
  3926.  */
  3927.  
  3928. void
  3929. Tk_PhotoExpand(handle, width, height)
  3930.     Tk_PhotoHandle handle;    /* Handle for the image to be expanded. */
  3931.     int width, height;        /* Desired minimum dimensions of the image. */
  3932. {
  3933.     PhotoMaster *masterPtr;
  3934.  
  3935.     masterPtr = (PhotoMaster *) handle;
  3936.  
  3937.     if (width <= masterPtr->width) {
  3938.     width = masterPtr->width;
  3939.     }
  3940.     if (height <= masterPtr->height) {
  3941.     height = masterPtr->height;
  3942.     }
  3943.     if ((width != masterPtr->width) || (height != masterPtr->height)) {
  3944.     ImgPhotoSetSize(masterPtr, width, height);
  3945.     Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0, masterPtr->width,
  3946.         masterPtr->height);
  3947.     }
  3948. }
  3949.  
  3950. /*
  3951.  *----------------------------------------------------------------------
  3952.  *
  3953.  * Tk_PhotoGetSize --
  3954.  *
  3955.  *    This procedure is called to obtain the current size of a photo
  3956.  *    image.
  3957.  *
  3958.  * Results:
  3959.  *    The image's width and height are returned in *widthp
  3960.  *    and *heightp.
  3961.  *
  3962.  * Side effects:
  3963.  *    None.
  3964.  *
  3965.  *----------------------------------------------------------------------
  3966.  */
  3967.  
  3968. void
  3969. Tk_PhotoGetSize(handle, widthPtr, heightPtr)
  3970.     Tk_PhotoHandle handle;    /* Handle for the image whose dimensions
  3971.                  * are requested. */
  3972.     int *widthPtr, *heightPtr;    /* The dimensions of the image are returned
  3973.                  * here. */
  3974. {
  3975.     PhotoMaster *masterPtr;
  3976.  
  3977.     masterPtr = (PhotoMaster *) handle;
  3978.     *widthPtr = masterPtr->width;
  3979.     *heightPtr = masterPtr->height;
  3980. }
  3981.  
  3982. /*
  3983.  *----------------------------------------------------------------------
  3984.  *
  3985.  * Tk_PhotoSetSize --
  3986.  *
  3987.  *    This procedure is called to set size of a photo image.
  3988.  *    This call is equivalent to using the -width and -height
  3989.  *    configuration options.
  3990.  *
  3991.  * Results:
  3992.  *    None.
  3993.  *
  3994.  * Side effects:
  3995.  *    The size of the image may change; if so the generic
  3996.  *    image code is informed.
  3997.  *
  3998.  *----------------------------------------------------------------------
  3999.  */
  4000.  
  4001. void
  4002. Tk_PhotoSetSize(handle, width, height)
  4003.     Tk_PhotoHandle handle;    /* Handle for the image whose size is to
  4004.                  * be set. */
  4005.     int width, height;        /* New dimensions for the image. */
  4006. {
  4007.     PhotoMaster *masterPtr;
  4008.  
  4009.     masterPtr = (PhotoMaster *) handle;
  4010.  
  4011.     masterPtr->userWidth = width;
  4012.     masterPtr->userHeight = height;
  4013.     ImgPhotoSetSize(masterPtr, ((width > 0) ? width: masterPtr->width),
  4014.         ((height > 0) ? height: masterPtr->height));
  4015.     Tk_ImageChanged(masterPtr->tkMaster, 0, 0, 0, 0,
  4016.         masterPtr->width, masterPtr->height);
  4017. }
  4018.  
  4019. /*
  4020.  *----------------------------------------------------------------------
  4021.  *
  4022.  * Tk_PhotoGetImage --
  4023.  *
  4024.  *    This procedure is called to obtain image data from a photo
  4025.  *    image.  This procedure fills in the Tk_PhotoImageBlock structure
  4026.  *    pointed to by `blockPtr' with details of the address and
  4027.  *    layout of the image data in memory.
  4028.  *
  4029.  * Results:
  4030.  *    TRUE (1) indicating that image data is available,
  4031.  *    for backwards compatibility with the old photo widget.
  4032.  *
  4033.  * Side effects:
  4034.  *    None.
  4035.  *
  4036.  *----------------------------------------------------------------------
  4037.  */
  4038.  
  4039. int
  4040. Tk_PhotoGetImage(handle, blockPtr)
  4041.     Tk_PhotoHandle handle;    /* Handle for the photo image from which
  4042.                  * image data is desired. */
  4043.     Tk_PhotoImageBlock *blockPtr;
  4044.                 /* Information about the address and layout
  4045.                  * of the image data is returned here. */
  4046. {
  4047.     PhotoMaster *masterPtr;
  4048.  
  4049.     masterPtr = (PhotoMaster *) handle;
  4050.     blockPtr->pixelPtr = masterPtr->pix24;
  4051.     blockPtr->width = masterPtr->width;
  4052.     blockPtr->height = masterPtr->height;
  4053.     blockPtr->pitch = masterPtr->width * 3;
  4054.     blockPtr->pixelSize = 3;
  4055.     blockPtr->offset[0] = 0;
  4056.     blockPtr->offset[1] = 1;
  4057.     blockPtr->offset[2] = 2;
  4058.     return 1;
  4059. }
  4060.